Skip to main content

C++ STL Vector Container – std::vector

Here you will learn about C++ STL Vector Container i.e. std::vector and various functions applicable on it.

Vector, as we discussed earlier vector is dynamic array that grows in one direction.

C++ STL Vector

Also Read: C++ STL Array Container – std::array

C++ STL Vector

Vectors are dynamic arrays. When we insert a new element or delete an element from vector, it has ability to resize itself automatically. Vector elements also stored in contiguous memory locations, so that they can traverse and accessed by iterators. Inserting and deleting at end takes constant , O(1) time. By using vectors we can avoid array_index_outof_bound exceptions.

Syntax of STL Vector

vector <data_type> vectorName;

Functions Used with Vector Container

push_back(): This is used to insert element into vector. It inserts element at the end of the vector.

[] operator: This operator returns the reference of the element positioned at index where we access like vectorName[index_position].

at(): This operator also useful to access the element at particular position.

front(): This returns the reference to the first element of the vector.

back(): This returns the reference to the last element of the vector.

Example program to show above mentioned functions:

#include<iostream>
#include<vector>

using namespace std;

int main(){
        vector<int> vec; // syntax for defining a vector
        
        // inserting elements into vector by push_back funtion
        for(int i=0;i<6;i++)
                vec.push_back(i);
        
        // accessing using [] operator
        for(int i=0;i<3;i++)
                cout<< vec[i] << " ";
        
        // accessing using at()
        for(int i=3;i<6;i++)
                cout << vec.at(i) << " ";
        
        cout << endl;
        
        // returning front element
        cout << vec.front() << endl;
        
        //returning last element
        cout << vec.back() << endl;
        
        return 0;
}

Output

0 1 2 3 4 5
0
5

size(): It gives the number of elements present in the vector.

max_size(): It gives the maximum number of elements that a vector can hold.

capacity(): We said that, vector is dynamic array which grow by inserting elements. When we declare it system allocates some space to it. Particular number of elements it can hold. If we insert more than that elements, system allocates some more space for it (at new location by free-up old space).

Capacity() returns how many items can be fit in the vector before it is “full”. Once full, adding new items will result in a new, larger block of memory being allocated and the existing items being copied to it.

resize(): It resize the vector, restrict to contain only some number of elements.

empty(): This is Boolean function. Returns whether the vector is empty or not.

Example Program to show above functions:

#include<iostream>
#include<vector>

using namespace std;

int main(){
        vector<int> vec; 
        for(int i=0;i<5;i++) vec.push_back(i);
        
        cout << "size of the vector is " << vec.size() << endl; // present number of elements
        cout << "Maximum size is " << vec.max_size() << endl; // maximum number of elements can hold
        cout << "Capacity of the vector is " << vec.capacity() << endl; //
        vec.resize(0); // restricting vector to contain zero elements
        vec.empty() ? cout << "vector is empty" << endl: cout << "vector is not empty " << endl; //checking empty conditon
        
        return 0;
}

Output

size of the vector is 5
Maximum size is 4611686018427387903
Capacity of the vector is 8
vector is empty

Vector with Iterator

begin(): Returns an iterator pointing to the first element of the vector.

end(): Returns an iterator pointing to the present last element of the vector.

rbegin(): Returns a reverse iterator pointing to the last element in the vector.  Used to move from last to first

rend(): Returns a reverse iterator pointing to the first element in the vector.

Example program:

#include<iostream>
#include<vector>

using namespace std;

int main(){
        vector<int> vec;
        vector<int> ::  iterator it1;
        vector<int> :: reverse_iterator it2;
        
        for(int i=0;i<5;i++) vec.push_back(i);
        
        // elements form start to end
        cout << "elements in the vector from start to end ";
        for(it1 = vec.begin(); it1!= vec.end();it1++)
                cout << *it1 << " ";
        
        cout << endl;
        
        // elements form end to start
        cout << "elements in the vector from end to start ";
        for(it2 = vec.rbegin(); it2!= vec.rend();it2++)
                cout << *it2 << " ";
        
        cout << endl;
        
        return 0;
}

Output

elements in the vector from start to end 0 1 2 3 4
elements in the vector from end to start 4 3 2 1 0

assign(): Assign new content to vector and resize.

pop_back(): This removes the element at the end of the vector. So that, size of the vector also reduced by 1.

insert(iterator, element): This inserts the element in vector before the position pointed by iterator. This insert method can be overloaded by third variable count. This says how many times the element to be inserted before the pointed position.

Example program to show above methods:

#include<iostream>
#include<vector>

using namespace std;

int main(){
        vector <int> vec1;
        vector <int> vec2;
        vector <int> :: iterator it;
        
        vec1.assign(4,100); // inserting element 100 into vector 4 times.
        it = vec1.begin();
        vec2.assign(it+1, vec1.end()); // inserts 3 elements of vec1
        cout << "Vector1 elements are " << endl;
        
        for(int i=0;i< vec1.size();i++)
                cout << vec1[i] << " ";
        
        cout << endl;
        cout << "Vector2 elements are " << endl;
        
        for(int i=0;i< vec2.size();i++)
                cout << vec2[i] << " ";
        
        cout << endl;
        
        vec2.push_back(10);
        cout << "new value inserted into vector2. Last element is " << vec2.back() << endl;
        vec2.pop_back();
        cout << "after pop_back operation last element of vector2 is " << vec2.back() << endl;
        
        vector <int> vec3(3,10);
        it = vec3.begin();
        it = vec3.insert(it,20); // this inserts element 20 as first element
        cout <<  "Now first element of vec3 is " << vec3.front();

        return 0;
}

Output

Vector1 elements are
100 100 100 100
Vector2 elements are
100 100 100
new value inserted into vector2. Last element is 10
after pop_back operation last element of vector2 is 100
Now first element of vec3 is 20

erase(): Removes the element pointed by the iterator position. This erase method can be overloaded with extra iterator that specifies the range to be removed.

Example program:

#include<iostream>
#include<vector>

using namespace std;

int main(){
        vector <int> vec;
        vector <int> :: iterator it;
        vec.push_back(100);
        
        for(int i=0;i<5;i++)
                vec.push_back(i);
        
        cout << "first element before erasing is " << vec.front() << endl;

        it = vec.begin();
        vec.erase(it); // removes first element of the vector
        cout << "first element after erasing is " << vec.front() << endl;
        
        vec.erase(vec.begin(), vec.end()); // this removes elements in the vector from first to last

        //checking vector empty or not
        vec.empty() ? cout << "vector is empty " << endl : cout << "Vector is not empty " <<endl;
        
        return 0;
}

Output

first element before erasing is 100
first element after erasing is 0
vector is empty

swap( vector1, vector2): This swaps the all elements of vector1 to vector2 and vector2 to vector1.

clear(): This removes the all elements of the vector.

Example program:

#include<iostream>
#include<vector>

using namespace std;

int main(){
        vector <int> vec1;
        vector <int> vec2;
        
        for(int i=1;i<6;i++)
                vec1.push_back(i);
        
        for(int i=11;i<16;i++)
                vec2.push_back(i);
        
        cout << "Vector1 elements before swapping are " << endl;
        for(int i=0;i<5;i++)
                cout << vec1[i] << " ";
        
        cout << endl;
        
        cout << "Vector2 elements before swapping are " << endl;
        for(int i=0;i<5;i++)
                cout << vec2[i] << " ";
        
        cout << endl;
        
        swap(vec1,vec2);
        
        cout << "Vector1 elements after swapping are " << endl;
        for(int i=0;i<5;i++)
                cout << vec1[i] << " ";
        
        cout << endl;
        
        cout << "Vector2 elements after swapping are " << endl;
        for(int i=0;i<5;i++)
                cout << vec2[i] << " ";
        
        cout << endl;
        
        // clearing vector1
        vec1.clear();
    //checking vector empty or not
        vec1.empty() ? cout << "vector is empty " << endl : cout << "Vector is not empty " <<endl;
        
        return 0;
}

Output

Vector1 elements before swapping are
1 2 3 4 5
Vector2 elements before swapping are
11 12 13 14 15
Vector1 elements after swapping are
11 12 13 14 15
Vector2 elements after swapping are
1 2 3 4 5
vector is empty

Comment below if you have queries or found any information incorrect in above tutorial for C++ stl vector container.

The post C++ STL Vector Container – std::vector appeared first on The Crazy Programmer.



from The Crazy Programmer http://www.thecrazyprogrammer.com/2017/07/stl-vector.html

Comments

  1. https://www.thecrazyprogrammer.com/2017/07/stl-array.html

    ReplyDelete

Post a Comment

Popular posts from this blog

dotnet sdk list and dotnet sdk latest

Can someone make .NET Core better with a simple global command? Fanie Reynders did and he did it in a simple and elegant way. I'm envious, in fact, because I spec'ed this exact thing out in a meeting a few months ago but I could have just done it like he did and I would have used fewer keystrokes! Last year when .NET Core was just getting started, there was a "DNVM" helper command that you could use to simplify dealing with multiple versions of the .NET SDK on one machine. Later, rather than 'switching global SDK versions,' switching was simplified to be handled on a folder by folder basis. That meant that if you had a project in a folder with no global.json that pinned the SDK version, your project would use the latest installed version. If you liked, you could create a global.json file and pin your project's folder to a specific version. Great, but I would constantly have to google to remember the format for the global.json file, and I'd constan

R vs Python for Machine Learning

There are so many things to learn before to choose which language is good for Machine Learning. We will discuss each and everything about R as well as Python and the situation or problem in which situation we have to use which language. Let’s start Python and R are the two most Commonly used Programming Languages for Machine Learning and because of the popularity of both the languages Novice or you can say fresher are getting confused, whether they should choose R or Python language to commence their career in the Machine learning domain. Don’t worry guys through this article we will discuss R vs Python for Machine Learning. So, without exaggerating this article let’s get started. We will start it from the very Basics things or definitions. R vs Python for Machine Learning Introduction R is a programming language made by statisticians and data miners for statistical analysis and graphics supported by R foundation for statistical computing. R also provides high-quality graphics and

Top Tips For PCB Design Layout

Are you thinking about designing a printed circuit board? PCBs are quite complicated, and you need to make sure that the layout that you choose is going to operate as well as you want it to. For this reason, we have put together some top tips for PCB design layout. Keep reading if you would like to find out more about this. Leave Enough Space One of the most important design tips for PCB layout is that you need to make sure that you are leaving enough space between the components. While many people might think that packing components closely is the best route to take, this can cause problems further down the line. This is why we suggest leaving extra space for the wires that will spread. This way, you’ll have the perfect PCB design layout. Print Out Your Layout Struggling to find out if your components sizes match? Our next tip is to print out your layout and compare the printed version to your actual components. Datasheets can sometimes come with errors, so it doesn’t hurt to do