Reputation: 21
I am trying to learn c++. I have understood few things.
I was trying to implement program using vector in c++ for dynamic array, while everything seems to work but one thing in particular cout
statement throws some weird error .
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> g1;
for (int i = 1; i <= 5; i++) {
g1.push_back(i);
}
cout << "This works"; // this cout works
cout << g1; // but this does not why ?
return 0;
}
Error that I am getting after running.
main.cpp: In function ‘int main()’:
main.cpp:18:7: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘std::vector<int>’)
cout << g1;
~~~~~^~~~~
Here is the program. I was trying to debug on hackerrank and I came across this problem. Why does not cout work for vector variable only? What am I missing?
Upvotes: 1
Views: 528
Reputation: 47794
There is no overload for operator<<
for std::vector<T>
. If you really wish to use operator<<
for std::vector<T>
, you will have to provide the implementation for it yourself, eg:
template <typename T>
std::ostream& operator<< (std::ostream& out, const std::vector<T>& vec) {
if ( !vec.empty() ) {
out << '{';
std::copy (std::cbegin(vec),
std::cend(vec),
std::ostream_iterator<T>(out, ", "));
out << "}";
}
return out;
}
Upvotes: 2
Reputation: 1910
cout
is a stream. You can write all the integral types (int
, long
, char
, short
, pointers etc.) and string
to a stream, but vector
is unsupported. If you want to print it, you may want to iterate through elements like this:
for (int i: g1) {
cout << i << ' ';
}
Or you can also implement operator<<
for vector:
template <typename T> ostream& operator<<(ostream& lhs, vector<T> rhs) {
for (T i: rhs) {
lhs << i;
}
return lhs;
}
Then you will be able to use cout << g1;
.
Upvotes: 0
Reputation: 718
You need to print vector like below code snippet:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> g1;
for (int i = 1; i <= 5; i++) {
g1.push_back(i);
}
cout << "This works"; // this cout works
for (int i = 0; i < g1.size(); ++i)
cout << g1[i] << ' ';
return 0;
}
Upvotes: 0