使用迭代器遍历vector容器怎样获取值
时间: 2023-07-16 07:15:01 浏览: 59
可以使用迭代器来遍历vector容器,并通过解引用操作符 * 获取当前迭代器所指向的元素的值。以下是示例代码:
```
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 使用迭代器遍历vector并输出元素值
for (auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
```
输出结果为:1 2 3 4 5。在上述代码中,使用auto关键字定义迭代器it,使用begin()和end()方法分别获取vector容器的起始位置和结束位置的迭代器。在for循环中,每次迭代都通过解引用操作符 * 获取当前迭代器所指向的元素的值,并输出到控制台。
相关问题
如何用迭代器遍历容器?
可以使用迭代器来遍历容器,具体操作如下:
1. 使用 begin() 函数获取容器的起始迭代器,使用 end() 函数获取容器的结束迭代器。
2. 使用 while 或 for 循环结合迭代器来遍历容器。
3. 在每次迭代中,使用迭代器访问容器中的元素,可以通过解引用运算符 * 或 -> 来访问元素。
4. 对于 const 容器,需要使用 const_iterator 来定义迭代器,以保证不会修改容器中的元素。
下面是一个使用迭代器遍历 vector 容器的例子:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v{1, 2, 3, 4, 5};
// 使用迭代器遍历容器
for (auto it = v.begin(); it != v.end(); ++it) {
cout << *it << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
1 2 3 4 5
```
注意,在使用迭代器遍历容器时,需要注意迭代器的失效问题,避免访问无效的迭代器。此外,在使用迭代器访问容器元素时,需要确保容器不为空,避免出现访问越界的问题。
vector的迭代器遍历
以下是两种C++中vector的迭代器遍历的例子:
1. 使用普通迭代器遍历vector容器:
```cpp
#include <iostream>
#include <vector>
using namespace std;
void traverseVector_2(vector<int> v) {
vector<int>::iterator it = v.begin();
for(; it != v.end(); ++it) {
cout << (*it) << " ";
}
cout << endl;
}
```
2. 使用简化的迭代器遍历vector容器:
```cpp
#include <iostream>
#include <vector>
using namespace std;
void traverseVector_2(vector<int> v) {
int i = 0;
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << "v[" << i++ << "]" << "=" << *it << endl;
}
}
```