访问vector的内容

Accessing contents of a vector

本文关键字:vector 访问      更新时间:2023-10-16

我需要访问一个向量的内容。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;
    }