≡ Menu

STL Tutorial: How to use C++ Vector with Example Program

Vector is an important part of a STL (Standard Template Library).

On a very high-level, STL library has lot of containers that are often used, and it has few methods that could be applied on those containers. Basically STL has several ready-to-use common classes that you can use in your C++ programming. We’ll cover STL in detail probably in a separate article.

Before we discuss about Vector, let us start with an array.

Typically, you’ll initialize an array as shown below. In this case, you reserve space for no more than 10 ints in the memory.

int array[10];

What if you need eleven int in your array?

Then you define dimension like DIM 10, that is a macro, and if you need to change that dimension you change the number.

In that case, you need to recompile the program, which is not practical in all situations.

You could hard code the array, leave the dimension out, and let C++ calculate the dimension of the array. Or you could use: calooc, free, malloc, realloc or sbrk.

In C++ those functions have been called obsolete, and you could use new and delete instead of the above functions for dynamic allocation.

C++ Vector Example Code

The following C++ code example shows how we can use Vector.

#include <iostream>
#include <vector>

using namespace std;

int
main(void)
{

//Space for vector of int, called iVector
vector <int> iVektor;

//we will add the elements at the end of vector
do
{

//space for next element of the vector
cout<<"Next Element->"; int iElement; cin>>iElement;

//to remove the element from the back use pop_back
iVektor.push_back(iElement);

cout<<"Size of the vector is ="<<iVektor.size()<<endl
    <<"Capacity of the vector="<<iVektor.capacity()<<endl;

cout<<"More elements yes(y)/no(n)->";
char cRespond; cin>>cRespond;

if((cRespond == 'y')||(cRespond=='Y')) continue;

break;

} while(true);

//display elements from begin to end
for(vector<int>::iterator i=iVektor.begin();
    i != iVektor.end();
    cout<<*i++<<endl); cout<<endl<<endl;

//display elements from end to begin
for(vector<int>::reverse_iterator r=iVektor.rbegin();
    r != iVektor.rend();
    cout<<*r++<<endl); cout<<endl<<endl;

cout<<"You wish to see the element->";int iIndex; cin>>iIndex;

//first method to dispaly n-th element of a vector
cout<<"At("<<iIndex<<")="
    <<iVektor.at(iIndex)<<endl
    <<"or like this=";

//one more approach to display one of vector elements
vector<int>::iterator p=iVektor.begin()+iIndex;cout<<*p<<endl;

int iRespond; cin>>iRespond;

return EXIT_SUCCESS;

}

In STL, somebody created class with several methods, you can just use them, and benefit from the accumulated work of several programmers who worked on STL.

Those classes are called with #include <vector> for example.

There are also other containers in C++ and they could be applied in appropriate situations.

Declare these classes as shown below:

template <typename T> class vector

Now, if you know how C++ template works, you could conclude that there are a number of elements that are of type user uses.

Some of the things you might be interested are implemented in methods: size, capacity, resize and so on. The methods are very easy to understand.

If some task is very often used they usually add that method in vector library.

One very important thing are the iterators, you use them like they are pointers, but you don’t need to know about their implementation. In some cases it could be useful to know how vectors are implemented, because you could estimate the speed of the algorithm.

To get the beginning of the vector you could use begin, but for the end there is method end. If you wish to use it backward you have: rbegin and rend.

And if you would like to get the element at certain position you should have at method that could be used in this manner:

iVector.at[positon];

Vectors are array alike data structures, that are good from the point of speed, if we need to access the arbitrary elements, and if we need to add the elements at the end, but they are not very good if you need to add the elements at the beginning or in the middle.

This leaves space for other containers like: stack, queue, list, map and etc. But this is a place for new discussion, which container to use in the situation you are in. This introduction to STL vector should be a good jumpstart for you to research further and improve your skill in this area.

Additional STL Vector Exercises

Use Vectors to solve the following problems in C++:

  1. Ask the user for the number of elements in the array, and import them from the keyboard. After you save them in the memory, copy them in similar array which will be sorted. Finally, display all the elements of the vectors, the sorted one and not sorted one.
  2. Create a container for at least 100 ints. Then you will be provided with second vector of 10 elements. You need to calculate how many of elements of the second vector are contained in the first one. Also need to calculate percent of how many elements are in vector, and how many are not.
  3. There are two vectors for which you don’t know the size in advance. But, the sizes are same all the time. You need to show the message, are those two vectors equal.
  4. In the vector of unknown size, and int type, you should count how many times one element is repeated.
  5. Create the solution that will keep the int elements in vector and use binary search to find are those elements contained in that particular vector. Enable user to be able to input elements as long as he/she needs to look for the elements.
  6. Unknown number of ints is stored in vector. You task is to show the one part, the beginning of the part of a vector, and display the elements till you reach the end of sub vector. Create solution that will be able to display the part of the vector backward.
  7. Merge two sorted vectors into one.
Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • Pratul February 21, 2014, 3:48 am

    Hello
    I am trying to run puppet agent on one of my slave server, but the ‘var’ memory of my slave server is getting filled with clientbucket file and than process is terminated as there is no more memory left.
    Each time I run ‘puppet agent -t’ i remove puppetdlck file from var/lib/puppet/state and revoke my key from master server after deleting ssl folder in var/lib/puppet. Can someone help what to do with the ‘var’ memory getting filled with client bucket files and process is terminated because of that.

  • bipbot February 21, 2014, 10:51 am

    Hi!
    In the “C++ Vector Example Code” you have some mistakes I believe. First in the first output line you have “Unesi sledeci element->” which is in serbian-croatian-bosnian language. I don’t believe that you left that in wrong language intentionally. Also later in the code there is output message “Capaciti of the vector=” where word capacity is misspelled.
    Thank you for your educational blog posts.
    Regards,
    bipbot

  • duskoKoscica February 25, 2014, 5:38 am

    Ok that is right, I left “Unesi sledeci element->” in my native language, that should be input of next element, or you have some better expresion. For word cacacity is also right but it would make it harder to….

    Oh sorry I misspeled the cacaciti it would be like (99,97,112,97,99,105,116,121) in 10 basis, in 16 basis it would be (63, 61, 70, 61, 63, 69, 74, 79), but for thos that know the binary it would be something like(01100011,0110001,01110000, 01100001, 01100011, 01101001, 01110100, 01111001). Hope people don’t hate me after this one!

  • Ramesh Natarajan February 25, 2014, 7:59 am

    @bipbot,

    Thanks for pointing it out. It is fixed now.

  • duskoKoscica February 25, 2014, 8:15 am

    Ok, now I need to say THX!

  • Gopi S April 23, 2014, 11:41 am

    The program may crash, if the index to view element at() is more than size().

  • duskoKoscica April 26, 2014, 2:17 pm

    if(index <0) exit(EXIT_FAILURE); and for the one you have noticed it might be good to limit the access to iVector.size(), but if you would like to have big vector it might become to big onece you have added to manny elements, so you would need to prevent im to grow to big, because it would go over all limits, for that you would need to figure out the maximum size of the area that could be occupied with your program. There is one more issue and it would be problem of inputing something that is not int into the vector, that is usually resolved with try block. But this thing would make program way harder to read.

  • duskoKoscica April 27, 2014, 1:09 am

    to solve that problem some people would use something like this, and it could be found in one nice book, #include … assert=0 && index<_size), but this approach would be more toward C side of C++. If you create the program with GUI it would be good idea to limit imput, so that you don't have problems to dill with. That might be the answer to your question.

  • DuskoKoscica June 9, 2014, 1:09 am

    For professional solutions you have garay

    for that you could look at> https://developer.gnome.org/glib/stable/glib-Arrays.html

    but this is for professional programmers.