C++ – Displaying contents of a vector container in C++

c++stlvector

The following is a C++ program using STL vector container. Just wanted to know why the display() function is not printing the vector contents to the screen. If displaying the size() line is commented out, display() function works fine.

#include <iostream>
#include <vector>

using namespace std;

void display(vector<int> &v)
{
    for(int i; i<v.size(); i++)
    {
        cout << v[i] << " ";
    }
    cout << "\n" << endl;
}

int main()
{
    vector<int> v;
    cout << "Size of Vector=" << v.size() << endl;

    //Putting values into the vector
    int x;
    cout << "Enter five integer values" << endl;
    for(int i; i<5; i++)
    {
        cin >> x;
        v.push_back(x);
    }
    //Size after adding values
    cout << "Size of Vector=" << v.size() << endl;

    //Display the contents of vector
    display(v);

    v.push_back(6);

    //Size after adding values
    cout << "Size of Vector=" << v.size() << endl;

    //Display the contents of vector
    display(v);

}

Output:

Size of Vector=0

Enter five integer values

1

2

3

4

5

Size of Vector=5


Size of Vector=6

Best Solution

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.