[英]How do I iterate over a Constant Vector?
I have a vector of Student which has a field name. 我有一个带有字段名称的Student向量。
I want to iterate over the vector. 我想遍历向量。
void print(const vector<Student>& students)
{
vector<Student>::iterator it;
for(it = students.begin(); it < students.end(); it++)
{
cout << it->name << endl;
}
}
This is apparently illegal in C++. 在C ++中,这显然是非法的。
Please help. 请帮忙。
You have two (three in C++11) options: const_iterator
s and indexes (+ "range-for" in C++11) 您有两个(在C ++ 11中为三个)选项:
const_iterator
和索引(在C ++ 11中为+“ range-for”)
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
}
Use const_iterator
instead. 请
const_iterator
。 An iterator
allows modification of the vector
, so you can't get one from a const
container. iterator
允许修改vector
,因此您不能从const
容器中获得一个。
Also, the idiomatic way to write this loop uses it != students.end()
instead of <
(though this should work on a vector
). 同样,编写此循环的惯用方式是使用
it != students.end()
而不是<
(尽管它应在vector
上工作)。
C++11 style: C ++ 11样式:
void print(const vector<Student>& students) {
for(auto const& student : students) {
cout << student.name << endl;
}
}
代替vector<Student>::iterator
,使用vector<Student>::const_iterator
。
void print(const vector<Student>& students)
{
vector<Student>::const_iterator it; // const_iterator
for(it = students.begin(); it != students.end(); it++)
{
cout << it->name << endl;
}
}
void print(const vector<Student>& students)
{
for(auto it = students.begin(); it != students.end(); ++it)
{
cout << it->name << endl;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.