How do I iterate over a Constant Vector?(如何迭代常量向量?)
问题描述
我有一个包含字段名称的 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
}
这篇关于如何迭代常量向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何迭代常量向量?


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01