c++如何输出vector
时间: 2023-11-07 18:56:44 浏览: 56
要输出一个vector,你可以使用循环来遍历vector中的每个元素,并使用cout将其输出到屏幕上。以下是几种常见的方法:
方法一:使用迭代器
```
std::vector<char> path;// 添加元素到path中
for (std::vector<char>::const_iterator i = path.begin(); i != path.end(); ++i) {
std::cout << *i << ' ';
}
```
方法二:使用范围for循环
```
std::vector<char> path;
// 添加元素到path中
for (const auto& i : path) {
std::cout << i << ' ';
}
```
方法三:重载操作符<<
```
#include <iterator> // for std::ostream_iterator
#include <algorithm> // for std::copy
template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& v) {
if (!v.empty()) {
out << '[';
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(out, ", "));
out << "\b\b]";
}
return out;
}
std::vector<char> path;
// 添加元素到path中
std::cout << path;
```
方法四:使用typedef增加可读性
```
typedef std::vector<char> Path;
Path path;
// 添加元素到path中
for (Path::const_iterator i = path.begin(); i != path.end(); ++i) {
std::cout << *i << ' ';
}
```