我需要访问矢量的内容。向量包含一个结构,我需要循环遍历向量并访问结构成员。
如何使用for循环和向量迭代器?
答案 0 :(得分:5)
使用迭代器或[]
:
// 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;
}
答案 1 :(得分:2)
所有STL容器都提供一个名为 Iterators 的通用接口来访问STL容器的内容。这里的优点是如果您需要稍后更改STL容器(您发现特定容器不符合您的要求并希望更改为新容器)的时间,您的代码将更加松散地耦合,如Iterator界面不会改变。
<强> Online Demo 强>:
#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;
}