访问矢量的内容

use*_*630 2 c++ iterator vector

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

我怎么能用for循环和向量迭代器呢?

sha*_*oth 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 使用支持新的C++ 11标准的新编译器(如VS2010或gcc 4.4(至少)),编写更少:`for(auto it = vec.begin(); it!= vec.end() ;它++)` (2认同)