阅读量:144
在C++中,可以使用以下几种方法来遍历Vector容器:
- 使用迭代器遍历:
#include
#include
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 使用迭代器遍历
for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
- 使用auto关键字和范围for循环遍历:
#include
#include
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 使用auto关键字和范围for循环遍历
for (auto& num : vec) {
std::cout << num class="hljs-string">" ";
}
return 0;
}
- 使用STL算法中的for_each函数遍历:
#include
#include
#include
void print(int num) {
std::cout << num class="hljs-string">" ";
}
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 使用for_each函数遍历
std::for_each(vec.begin(), vec.end(), print);
return 0;
}
以上是几种常用的遍历Vector容器的方法,在实际开发中可以根据具体需求选择合适的方式来遍历Vector容器。