访问vector的内容
Accessing contents of a vector
我需要访问一个向量的内容。vector包含一个结构体,需要循环遍历vector并访问结构体成员。
如何使用for循环和vector迭代器实现这一点?
使用迭代器或[]
:
// 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;
}
所有STL容器都提供一个名为Iterators的公共接口来访问STL容器的内容。这样做的好处是,如果您稍后需要更改STL容器(您发现特定的容器不适合您的需求,并希望更改为新的容器),您的代码将更加松散耦合,因为Iterator接口不会更改。
<在线演示/strong>:
#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 的随机访问迭代器给出与指针不同的内存地址?
- 使用 std::vector<double> 访问由 std::unique_ptr<double[2] 管理的数据>
- 访问 std:vector 的类成员 std:vector 在一个类中与另一个 std:vector
- 通过引用传递时访问std::vector的元素
- SFML访问std::vector内的数组
- 使用静态 std::vector 类成员时出现访问冲突
- 如何从 boost::container::vector<std::string>::iterator 访问索引和对象?
- 访问"std::vector"的保留但未调整大小的内存作为原始内存是否安全?
- 访问类的 std::vector 与 for 循环中的 custum 类对象
- 如何在C++中从模板化类访问 std::vector 数据
- Vector::p ush_back() 给出读取访问冲突
- 如何访问vector<pair<int, pair<int, int>>> D[20]?
- 当从其他方法返回 vector 时,C++无法访问矢量元素
- Vector访问中出现内存损坏错误
- 是否可以进行编译,以使错误的std::vector访问调用退出程序,并显示有用的错误消息
- 从 vector 访问时,我的可变类的属性不会更改。(调试中)
- 优化' std::vector operator [] ' (vector访问),当它成为瓶颈时
- 从vector访问对象时遇到麻烦
- 模板函数和vector访问
- c++ vector访问违反读取位置