Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying contents of a vector container in C++

Tags:

c++

stl

vector

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
like image 897
heapuser Avatar asked Mar 17 '12 17:03

heapuser


2 Answers

If you use compiler versions g++ 11 or more than then you simply use:

#include <iostream>
#include <vector>

using namespace std;

int main(){
   vector<int> v;
   int x;
   cout << "Enter five integer values" << endl;
   for(int i=0; i<5; i++)
   {
        cin >> x;
        v.push_back(x);
   }

   for (auto i: v)
      cout<< i <<endl;

}
like image 84
Nahid Hasan Avatar answered Oct 28 '22 19:10

Nahid Hasan


You are not initializing your variables. for(int i = 0; not for(int i;

like image 39
YXD Avatar answered Oct 28 '22 19:10

YXD