Reputation: 81
I want to print out the contents of a std::vector
in C++.
Here is what I have:
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> v;
copy_n(istream_iterator<int>(cin), 5, back_inserter(v));
return 0;
}
Can I print the contents of the std::vector
with the same method?
Upvotes: 1
Views: 349
Reputation: 172894
Yes, you can do it by passing the iterator and the size of the vector
and std::ostream_iterator
to std::copy_n
.
std::copy_n(v.begin(), v.size(), std::ostream_iterator<int>(std::cout, " "));
Upvotes: 2
Reputation: 32722
Yes. You need to iterate through the vector and std::copy
the contents to the output stream with the help of std::ostream_iterator.
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
Upvotes: 4