c++中vector读取容器元素
时间: 2023-07-15 14:11:54 浏览: 46
可以使用下标访问符或迭代器来读取vector容器中的元素。
使用下标访问符:
```
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec{1, 2, 3, 4, 5};
std::cout << "The element at index 2 is: " << vec[2] << std::endl;
return 0;
}
```
输出结果:
```
The element at index 2 is: 3
```
使用迭代器:
```
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec{1, 2, 3, 4, 5};
auto it = vec.begin() + 2; // 获取第3个元素的迭代器
std::cout << "The element at index 2 is: " << *it << std::endl;
return 0;
}
```
输出结果:
```
The element at index 2 is: 3
```