std::cout << v does not compile: the standard library has no operator<< for std::vector. Loop over it with a range-based for: for (const auto& x : v) std::cout << x << ' ';. To get [1, 2, 3] without a trailing comma, print the separator before every element except the first, and put that loop in a function or an operator<< template you reuse.
Python prints a list with print(xs); C++ makes you write the loop, and in C++20 std::format cannot print a whole vector either. The good news is that the loop is three lines, and one small template makes std::cout << v work for vectors, nested vectors, sets and maps. The sections below cover the loop with a clean separator, a reusable operator<<, the std::copy one-liner, indices and aligned columns with std::format, and the element types whose output surprises people. Each example runs on this page: hit Run, then edit the code and run it again.
1A range-based for loopRecommended
for (const auto& x : v) visits every element in order. The const auto& matters for anything bigger than a number: plain auto would copy each std::string just to print it. Printing x << ' ' leaves a separator after the last element, so the reusable version below starts with an empty separator and switches it to ", " after the first element. Because print is a template, the same function prints a vector of any type that << already handles.
#include <iostream> #include <string> #include <vector> // Prints [a, b, c]: the separator goes before every element except the // first, so there is no trailing comma to clean up template <typename T> void print(const std::vector<T>& v) { std::cout << '['; const char* sep = ""; for (const auto& x : v) { std::cout << sep << x; sep = ", "; } std::cout << "]\n"; } int main() { std::vector<int> nums{3, 1, 4, 1, 5}; // The plain loop: const auto& reads each element without copying it for (const auto& n : nums) { std::cout << n << ' '; } std::cout << '\n'; print(nums); print(std::vector<std::string>{"red", "green", "blue"}); print(std::vector<double>{0.5, 2.25}); print(std::vector<int>{}); // empty: just the brackets }
Output
The plain loop prints 3 1 4 1 5 with a space at the end, which is fine for a quick look at the data. print gives [3, 1, 4, 1, 5], [red, green, blue] and [0.5, 2.25], and an empty vector prints [] with no special case, because the loop body never runs. Avoid the other common trick, if (i != v.size() - 1) in an index loop: v.size() is unsigned, so on an empty vector v.size() - 1 wraps around to a huge number instead of -1.
2Overload operator<< for vectors and other containers
To write std::cout << v like any other value, define operator<< yourself. A C++20 template constrained to std::ranges::input_range covers std::vector, std::set, std::array and nested vectors at once; the requires clause leaves strings out, since they are ranges of char that already print as text. A map is a range of std::pair, so the example adds a pair overload, declared first so the range template can find it. Two small templates answer the "pretty-print STL containers" question.
#include <concepts> #include <iostream> #include <map> #include <ranges> #include <set> #include <sstream> #include <string> #include <string_view> #include <utility> #include <vector> // Declare both overloads before either body, so each can use the other: // a map holds pairs, and a vector can hold vectors template <typename A, typename B> std::ostream& operator<<(std::ostream& os, const std::pair<A, B>& p); // Any range except strings, which already print as text template <std::ranges::input_range R> requires(!std::convertible_to<const R&, std::string_view>) std::ostream& operator<<(std::ostream& os, const R& range); template <typename A, typename B> std::ostream& operator<<(std::ostream& os, const std::pair<A, B>& p) { return os << '(' << p.first << ", " << p.second << ')'; } template <std::ranges::input_range R> requires(!std::convertible_to<const R&, std::string_view>) std::ostream& operator<<(std::ostream& os, const R& range) { os << '['; const char* sep = ""; for (const auto& x : range) { os << sep << x; sep = ", "; } return os << ']'; } int main() { std::vector<int> v{1, 2, 3}; std::cout << v << '\n'; std::vector<std::vector<int>> grid{{1, 2}, {3, 4}, {}}; std::cout << grid << '\n'; std::vector<std::string> words{"hi", "there"}; std::cout << words << '\n'; // The same operator prints other containers too std::map<std::string, int> ages{{"Bo", 31}, {"Ada", 36}}; std::cout << ages << '\n'; std::set<char> letters{'c', 'a', 'b'}; std::cout << letters << '\n'; // Any ostream works, so a string stream turns a vector into a string std::ostringstream out; out << v; std::string text = out.str(); std::cout << text << " has " << text.size() << " chars\n"; }
Output
A nested vector prints as [[1, 2], [3, 4], []] because the inner os << x calls the same template, and the map prints as [(Ada, 36), (Bo, 31)], sorted by key. Writing into a std::ostringstream instead of std::cout turns the vector into a std::string: [1, 2, 3] has 9 chars. Two limits: never put these overloads in namespace std (adding declarations there is undefined behaviour), and code inside std does not see them. With a global operator<<(std::ostream&, const std::vector<int>&), std::copy(grid.begin(), grid.end(), std::ostream_iterator<std::vector<int>>(std::cout)) fails to compile, because the lookup inside ostream_iterator searches only std. Calls from your own code, as here, work.
3One line: std::copy and std::ostream_iterator
The classic one-liner copies the vector into an std::ostream_iterator, an output iterator that writes each value it receives to a stream, followed by a delimiter. C++20's std::ranges::copy takes the vector itself, and combined with a view it prints part of the vector or prints it backwards without copying it. std::ranges::for_each with a lambda covers the case where each element needs more than a plain <<.
#include <algorithm> #include <iostream> #include <iterator> #include <ranges> #include <vector> int main() { std::vector<int> v{10, 20, 30, 40}; // ostream_iterator writes its delimiter after EVERY element, // so the line ends in ", " std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, ", ")); std::cout << '\n'; // No trailing separator: copy all but the last, then print the last if (!v.empty()) { std::copy(v.begin(), v.end() - 1, std::ostream_iterator<int>(std::cout, ", ")); std::cout << v.back() << '\n'; } // The ranges version takes the vector itself, or a view of it std::ranges::copy(v | std::views::reverse, std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; std::ranges::copy(v | std::views::take(2), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; // for_each with a lambda when each element needs more than << std::ranges::for_each(v, [](int x) { std::cout << x / 10 << ' '; }); std::cout << '\n'; }
Output
The catch is in the first line: ostream_iterator writes the delimiter after every element, the last one included, so it prints 10, 20, 30, 40, . Copying all but the last and printing v.back() separately gives 10, 20, 30, 40; the !v.empty() guard matters, because v.end() - 1 on an empty vector points before the start. views::reverse prints 40 30 20 10 and views::take(2) prints 10 20 . For anything beyond a quick dump, the loop from section 1 is easier to read.
4Indices, columns and 2D vectors with std::format
When you need the index next to each element, loop with a std::size_t counter, the same unsigned type as v.size(). std::format (C++20) cannot format a whole vector, but it formats each element with a width, an alignment and a precision, which is what you need to line up numbers or print a 2D vector as a grid. For more format specs, see formatting a string.
#include <cstddef> #include <format> #include <iostream> #include <string> #include <vector> int main() { std::vector<std::string> names{"Ada", "Grace", "Linus"}; // Index and value: std::size_t is the type of names.size() for (std::size_t i = 0; i < names.size(); ++i) { std::cout << std::format("{}: {}\n", i, names[i]); } // C++20 std::format works on one element at a time: // width 7, right-aligned, 2 decimal places std::vector<double> prices{3.5, 12.0, 0.125}; for (double p : prices) { std::cout << std::format("[{:>7.2f}]", p); } std::cout << '\n'; // A 2D vector: one row per line, every cell 4 characters wide std::vector<std::vector<int>> grid{{1, 2, 3}, {40, 50, 60}, {700, 8, 9}}; for (const auto& row : grid) { for (int cell : row) { std::cout << std::format("{:>4}", cell); } std::cout << '\n'; } }
Output
{:>7.2f} right-aligns each price in 7 characters with 2 decimals: [ 3.50][ 12.00][ 0.12]. The last one is 0.12, not 0.13: 0.125 is exactly halfway, and std::format rounds a tie to the even digit. The grid prints one row per line with every cell 4 characters wide, so 700, 8 and 9 line up under the rows above. In C++23, std::format("{}", v) and std::println("{}", v) print a whole vector, brackets and commas included; this page compiles as C++20, where that line fails with std::formatter must be specialized for each type being formatted.
5Element types that print wrong
Whatever the method, each element goes through <<, and a few element types print something other than what people expect. std::uint8_t and std::int8_t are character types, double stops at 6 significant digits, std::vector<bool> prints digits, and strings that are empty or contain spaces become impossible to tell apart.
#include <cstdint> #include <iomanip> #include <iostream> #include <string> #include <vector> int main() { // uint8_t is an unsigned char, so << prints the characters std::vector<std::uint8_t> bytes{72, 105, 33}; for (auto b : bytes) { std::cout << b << ' '; } std::cout << '\n'; // Unary + promotes each one to int, which prints the number for (auto b : bytes) { std::cout << +b << ' '; } std::cout << '\n'; // double: 6 significant digits unless you ask for more std::vector<double> d{0.1 + 0.2, 1.0 / 3, 1e10 / 3}; for (double x : d) { std::cout << x << ' '; } std::cout << '\n' << std::setprecision(17); for (double x : d) { std::cout << x << ' '; } std::cout << '\n' << std::setprecision(6); // the setting sticks: reset it // vector<bool> prints 1 and 0; boolalpha prints the words std::vector<bool> flags{true, false, true}; for (bool f : flags) { std::cout << f << ' '; } std::cout << '\n' << std::boolalpha; for (bool f : flags) { std::cout << f << ' '; } std::cout << '\n' << std::noboolalpha; // Strings: spaces and empty elements disappear; std::quoted shows them std::vector<std::string> words{"a b", "", "c"}; for (const auto& w : words) { std::cout << w << ' '; } std::cout << '\n'; for (const auto& w : words) { std::cout << std::quoted(w) << ' '; } std::cout << '\n'; }
Output
The bytes 72 105 33 print as H i ! until unary + promotes them to int. The doubles print as 0.3 0.333333 3.33333e+09 by default and as 0.30000000000000004 0.33333333333333331 3333333333.3333335 with std::setprecision(17), which shows the value really stored (see comparing floating-point numbers). The bools print 1 0 1 , or true false true after std::boolalpha. The words print as a b c , which hides both the space and the empty string; std::quoted prints "a b" "" "c". setprecision and boolalpha stay set on the stream, so the example resets them.
6Which should you use?
| Method | Trailing separator | Standard | Best for |
|---|---|---|---|
| for (const auto& x : v) | Avoidable | C++11 | Almost everything; wrap it in a function |
| template operator<< | None | C++20 (concepts) | std::cout << v for nested vectors, sets, maps |
| std::copy + ostream_iterator | Always | C++98 | A quick one-line dump |
| std::ranges::copy(v | view, …) | Always | C++20 | Part of a vector, or reversed |
| index loop + std::format | You choose | C++20 | Indices, aligned columns, 2D grids |
| std::println("{}", v) | None | C++23 | The one-liner, once your compiler is on C++23 |
Frequently asked questions
Why does std::cout << v not compile for a vector?
The standard library defines operator<< for numbers, characters and strings, but not for containers, so GCC reports no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'std::vector<int>'). Print the elements in a loop, or define your own operator<< template outside namespace std, as in section 2.
Can std::format or std::print print a whole vector?
Only from C++23, which added range formatting: std::println("{}", v) prints the whole vector in brackets with commas, and nested vectors and maps work too. In C++20, std::format("{}", v) fails to compile with std::formatter must be specialized for each type being formatted, so format one element at a time in a loop.
How do I print a vector without a trailing comma?
Print the separator before each element instead of after it, starting with an empty one: const char* sep = ""; for (const auto& x : v) { std::cout << sep << x; sep = ", "; }. It needs no index and handles an empty vector. With std::ostream_iterator, copy all but the last element and print v.back() on its own, after checking that the vector is not empty.
How do I print a vector of my own struct?
Give the struct its own operator<<, usually as a friend: friend std::ostream& operator<<(std::ostream& os, const Point& p) { return os << p.x << ',' << p.y; }. The loops on this page, the operator<< template from section 2 and std::ostream_iterator<Point> then all print the vector, because the operator is found through the struct's own namespace.
How do I convert a vector to a string in C++?
Write it into a std::ostringstream with the same loop or operator<< you use for printing, then call .str(): section 2 turns {1, 2, 3} into the 9-character string [1, 2, 3]. For a std::vector<char>, std::string(v.begin(), v.end()) builds the string from the characters directly.
Why does my vector<uint8_t> print letters or nothing at all?
std::uint8_t is an alias for unsigned char, so << prints the character with that code: 72 prints as H, and small values such as 0 or 7 are invisible control characters. Print +b or static_cast<int>(b) to get the number. The same applies to std::int8_t and std::vector<char>.