如何迭代常量向量?
我有一个包含字段名称的 Student 向量.
I have a vector of Student which has a field name.
我想遍历向量.
void print(const vector<Student>& students)
{
vector<Student>::iterator it;
for(it = students.begin(); it < students.end(); it++)
{
cout << it->name << endl;
}
}
这在 C++ 中显然是非法的.
This is apparently illegal in C++.
请帮忙.
推荐答案
您有两个(C++11 中的三个)选项:const_iterator
s 和索引(C 中的range-for"++11)
You have two (three in C++11) options: const_iterator
s and indexes (+ "range-for" in C++11)
void func(const std::vector<type>& vec) {
std::vector<type>::const_iterator iter;
for (iter = vec.begin(); iter != vec.end(); ++iter)
// do something with *iter
/* or
for (size_t index = 0; index != vec.size(); ++index)
// do something with vec[index]
// as of C++11
for (const auto& item: vec)
// do something with item
*/
}
对于迭代器,您应该更喜欢使用 !=
而不是 <
- 后者不适用于所有迭代器,前者可以.使用前者,您甚至可以使代码更通用(这样您甚至可以在不触及循环的情况下更改容器类型)
You should prefer using !=
instead of <
with iterators - the latter does not work with all iterators, the former will. With the former you can even make the code more generic (so that you could even change the container type without touching the loop)
template<typename Container>
void func(const Container& container) {
typename Container::const_iterator iter;
for (iter = container.begin(); iter != container.end(); ++iter)
// work with *iter
}
相关文章