Introduction to vectors in C++

What is a vector?

Vector in C++ is similar to arrays, You can say vectors are more than arrays. It performs dynamic array functionality with taking care of memory management(freeing,allocating)

Vector combines the advantage of both static and dynamic arrays. It will automatically deletes the memory allocated for the vector like static array and like dynamic array you can have variable size, there is no need of specifying the size at the beginning.


In order to use vectors in your programs, you have to include vector header file

#include <vector>

As vectors are present in std namespace, you have to declare

using namespace std;

To declare a vector of integers

vector<int> var_name;

If you have not specified using namespace std;

std::vector<int> var_name;

Now to check the size of the vector, you can use size() member function of the vector class.

var_name.size();

Initially it will return 0.

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int> int_vector;
    cout << "Size of vector " << int_vector.size();
    return 0;
}

If you want to have a integer vector of size 10.

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int> int_vector(10);
    cout << "Size of vector " << int_vector.size();
    return 0;
}


You can access the vector in the same way as you access array by using [] operator

To access third element of the int_vector:
cout << int_vector[2];

But problem using this approach is that it will not validate whether actually an element exist at this location. What if you are having a vector of size 20, and you are accessing 30 th element.

In order to avoid this,you can use the at() function which performs boundary checking.

cout << int_vector.at(2);

Suppose you have allocated an vector of size 10, and now you have a requirement of having an additional element, in this case you can use push_back function to resize the vector and add it to the end of the vector.

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int> int_vector;
    cout << "Size of vector " << int_vector.size()<<endl;
    int numbr;
    cout << "Enter your number: ";
    cin >> numbr;
    int_vector.push_back(numbr);
    cout << "Size of vector " << int_vector.size()<<endl;
    return 0;
}





Comments

Popular posts from this blog

bb.utils.contains yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig

PR, PN and PV Variable in Yocto