21xrx.com
2024-06-03 05:47:15 Monday
登录
文章检索 我的文章 写文章
C++如何遍历结构体元素?
2023-06-22 15:18:32 深夜i     --     --
C++ 结构体 遍历 元素

C++是一种面向对象的编程语言,在开发过程中,我们通常需要使用结构体(struct)来组织数据。对于一个结构体,如何遍历其中的元素呢?

一、使用"."操作符

结构体中的元素可以通过"."操作符进行访问,例如:

struct Student

 int id;

 string name;

 double score;

;

Student s = 90 ;

cout << "id:" << s.id << endl;

cout << "name:" << s.name << endl;

cout << "score:" << s.score << endl;

二、使用指针和"->"操作符

我们也可以定义一个指向结构体的指针,并通过"->"操作符来访问结构体中的元素,例如:

struct Student

 int id;

 string name;

 double score;

;

Student s = 90 ;

Student *p = &s;

cout << "id:" << p->id << endl;

cout << "name:" << p->name << endl;

cout << "score:" << p->score << endl;

三、使用for循环遍历结构体数组

如果结构体是一个数组,我们可以使用for循环来遍历每个元素,然后通过"."或"->"操作符访问每个元素的具体信息,例如:

struct Student

 int id;

 string name;

 double score;

;

Student stu[3] = { "Tom", 85, 92 };

for (int i = 0; i < 3; i++) {

 cout << "id:" << stu[i].id << endl;

 cout << "name:" << stu[i].name << endl;

 cout << "score:" << stu[i].score << endl;

}

总结:

以上就是C++遍历结构体元素的几种方法,我们可以根据实际需求选择不同的方法来访问结构体中的元素。在使用"."或"->"操作符时,要注意结构体中的变量是否公有(public),否则无法访问。在遍历结构体数组时,要使用合适的循环语句来遍历每个元素,保证代码的简洁和高效。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复