【发布时间】:2011-11-10 11:21:51
【问题描述】:
我需要访问向量的内容。向量包含一个结构,我需要遍历该向量并访问结构成员。
如何使用 for 循环和向量迭代器来做到这一点?
【问题讨论】:
-
请提供更多详细信息。您使用什么数据类型?
-
vec[i] 有什么问题? , 意思是 - [] 运算符?
我需要访问向量的内容。向量包含一个结构,我需要遍历该向量并访问结构成员。
如何使用 for 循环和向量迭代器来做到这一点?
【问题讨论】:
使用迭代器或[]:
// assuming vector will store this type:
struct Stored {
int Member;
};
//and will be declared like this:
std::vector<Stored> vec;
// here's how the traversal loop looks like with iterators
for( vector<Stored >::iterator it = vec.begin(); it != vec.end(); it++ ) {
it->Member;
}
// here's how it looks with []
for( std::vector<Stored>::size_type index = 0; index < vec.size(); index++ ) {
vec[index].Member;
}
【讨论】:
for (auto it = vec.begin(); it != vec.end(); it++)。
所有 STL 容器都提供了一个名为 Iterators 的通用接口来访问 STL 容器的内容。这里的好处是,如果您需要在以后更改 STL 容器(您发现特定容器不适合您的要求并想更改为新容器),您的代码更松散耦合,因为迭代器界面不会改变。
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct Student
{
string lastName;
string firstName;
};
int main()
{
Student obj;
obj.firstName = "ABC";
obj.lastName = "XYZ";
vector<Student> students;
students.push_back(obj);
vector<Student>::iterator it;
cout << "students contains:";
for ( it=students.begin() ; it != students.end(); ++it )
{
cout << " " << (*it).firstName;
cout << " " << (*it).lastName;
}
return 0;
}
【讨论】:
vector::push_back() 或vector::insert() 方法填充向量,一旦向量被元素填充,您可以使用[] 运算符访问\修改这些元素。请注意,您需要通过检查vector::size()来检查[]的索引是否有效,否则会导致Undefined Behavior。