【问题标题】:Accessing contents of a vector访问向量的内容
【发布时间】:2011-11-10 11:21:51
【问题描述】:

我需要访问向量的内容。向量包含一个结构,我需要遍历该向量并访问结构成员。

如何使用 for 循环和向量迭代器来做到这一点?

【问题讨论】:

  • 请提供更多详细信息。您使用什么数据类型?
  • vec[i] 有什么问题? , 意思是 - [] 运算符?

标签: c++ vector iterator


【解决方案1】:

使用迭代器或[]:

// 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;
}

【讨论】:

  • 有了支持新 C++11 标准的新编译器(如 VS2010 或 gcc 4.4(至少)),写起来就更少了:for (auto it = vec.begin(); it != vec.end(); it++)
  • 现在我只需要访问向量的某些成员。我需要矢量内容的索引。只有当我找到所需的索引时,我才会读取结构成员。我怎么做 ?因为 for 循环使用 .begin() 和 .end()
  • @user1039630:更新,添加了另一个使用索引的版本
  • 如何使用 std::foreach 做同样的事情?
【解决方案2】:

所有 STL 容器都提供了一个名为 Iterators 的通用接口来访问 STL 容器的内容。这里的好处是,如果您需要在以后更改 STL 容器(您发现特定容器不适合您的要求并想更改为新容器),您的代码更松散耦合,因为迭代器界面不会改变。

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;
    }

【讨论】:

  • 假设向量包含 100 个学生。现在我只想访问第 1 位、第 10 位、第 79 位学生的名字和姓氏。我该怎么做?
  • @user1039630:您使用vector::push_back()vector::insert() 方法填充向量,一旦向量被元素填充,您可以使用[] 运算符访问\修改这些元素。请注意,您需要通过检查vector::size()来检查[]的索引是否有效,否则会导致Undefined Behavior。
猜你喜欢
  • 1970-01-01
  • 2011-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多