Displaying contents of a vector container in C++

There is an idiomatic way for printing a vector out.

#include <algorithm>
#include <iterator>

//note the const
void display_vector(const vector<int> &v)
{
    std::copy(v.begin(), v.end(),
        std::ostream_iterator<int>(std::cout, " "));
}

This way is safe and doesn’t require you to keep track of the vectors size or anything like that. It is also easily recognisable to other C++ developers.

This method works on other container types too that do not allow random access.

std::list<int> l;
//use l

std::copy(l.begin(), l.end(),
          std::ostream_iterator<int>(std::cout, " "));

This works both ways with input too consider the following:

#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
    std::cout << "Enter int end with q" << std::endl;
    std::vector<int> v; //a deque is probably better TBH
    std::copy(std::istream_iterator<int>(std::cin),
              std::istream_iterator<int>(),
              std::back_inserter<int>(v));

    std::copy(v.begin(), v.end(),
              std::ostream_iterator<int>(std::cout, " "));
}

This version doesn’t require any hard coding of size or manual management of the actual elements.

Leave a Comment