Vectors

This short program shows an array and a vector with the exact same elements. Both use a for loop to display the contents.

There is no easy way to initialize the contents of a vector. If you are using a fixed number of elements such as the names of the months, it is easier and more efficient to use an array. If you are reading from a file and are not sure how many records are in the file, use a vector.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
#include <vector>
using namespace std;
int main() {
   int numbers[6]={5,12,3,17}; //the array has a fixed size of 6, the last 2 will be 0
   int count=sizeof(numbers)/sizeof(int);
   cout<<"There are "<<count<<" numbers\n";
   for(int i=0;i<count;i++) {
      cout<<numbers[i]<<endl;
   } //print each number
   
   vector<int> vnumbers; //the vector is empty but we can "push" as many int as we want
   vnumbers.push_back(5); //pushes onto the back, or end, of the vector.
   vnumbers.push_back(12);
   vnumbers.push_back(3);
   vnumbers.push_back(17);
   cout<<"\nThere are "<<vnumbers.size()<<" vnumbers\n";
   for(int v=0;v<vnumbers.size();v++) {
      cout<<vnumbers[v]<<endl;
   }//print each number
   system("pause");
   return 0;
}//main
CODE

NEXT: Search and erase from a vector