CPP STL Tutorial: std::vector and it’s operations.

In this chapter we shall learn about:

1. vector introduction.
2. vector declaration.
3. Multidimensional std::vector
4. Passing std::vector to function
5. vector member function to iterate over elements.
6. vector member function to check the capacity.
7. vector member function to access the elements.
8. vector member function to modify the elements.
9. How vector works internally? http://cs.brown.edu/~jak/proglang/cpp/stltut/tut.html
10. Do vector store in continuous memory or non continuous memory?
11. How to create 2D vector?
12. How to remove elements in 2D vector?

 

1. vector introduction.
———————————————————————————-

C++ vector can be thought as a dynamic array. It is one of the most widely used classes. Unlike arrays, we don’t need to specify the exact size at the time of declaration. Similar to arrays, it will hold the value of same types.

In order to use vector, you need to include below header file:
“#include<vector>”

vector is a template type. You can create vector of your own class.

2. vector declaration.
———————————————————————————-

Declaration of 1D vector:

Syntax:vector< object_type > variable_name;

Example:std::vector<int> myvector;

3. Multidimensional std::vector
———————————————————————————-

Declaration of 2D vector:

std::vector <std::vector<int> > vec2D

2D vector can also be initialized as below:

std::vector <NUMBER OF ELEMENTS, VALUE OF EACH ELEMENT>

So for a 2D vector having 5 rows and 4 column of all 1’s can be defined as below:

std::vector <std::vector > vec2D(5, std::vector(4, 1));

{
	1 , 1 , 1 , 1
	1 , 1 , 1 , 1
	1 , 1 , 1 , 1
	1 , 1 , 1 , 1
	1 , 1 , 1 , 1
}

4. Passing std::vector to function
———————————————————————————-

You can pass a vector in 2 ways:
1. Pass by value
2. Pass by reference

1. Pass by value

void func(vector<int> vec) 
{ 
   vec.push_back(30); 
} 
   
int main() 
{ 
    vector<int> vec; 
    vec.push_back(10); 
    vec.push_back(20); 
   
    func(vec); 
   
    // as we are passing by value, the vector will remain unchanged.
    for (int i=0; i<vec.size(); i++) 
       cout << vec[i] << " "; 
   
    return 0; 
} 

2. Pass by reference

void func(vector<int> &vec) 
{ 
   vec.push_back(30); 
} 
   
int main() 
{ 
    vector<int> vec; 
    vec.push_back(10); 
    vec.push_back(20); 
   
    func(vec); 
   
    // as we are passing by reference, the vector will be changed.
    for (int i=0; i<vec.size(); i++) 
       cout << vec[i] << " "; 
   
    return 0; 
} 
5. vector member function to iterate over elements.
———————————————————————————-
begin : It will return iterator to beginning
end   : It will return iterator to end
rbegin : It will return reverse iterator to reverse beginning
rend : It will return reverse iterator to reverse end
cbegin : It will return const_iterator to beginning  [C++ 11]
cend : It will return const_iterator to end [C++ 11]
Example:
#include <iostream>
#include <vector>
using namespace std;

int main(void)
{
    std::vector<int> myvector;
    for (int i=1; i<=5; i++) 
        myvector.push_back(i);

  std::cout << "myvector contains:";
  
  //iterate throughout the array, start from .begin till .end
  cout<<"Iterate using .begin and .end"<<endl;
  for (std::vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';
  
  cout<<"Iterate using .cbegin and .cend"<<endl;
 for (auto it = myvector.cbegin(); it != myvector.cend(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  cout<<"Iterate using .rbegin and .rend"<<endl;
 for (auto it = myvector.rbegin(); it != myvector.rend(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';
    
}

Output:

myvector contains:

Iterate using .begin and .end
1 2 3 4 5
Iterate using .cbegin and .cend
1 2 3 4 5
Iterate using .rbegin and .rend
5 4 3 2 1
6. vector member function to check the capacity.
———————————————————————————-
size : It will return size
max_size : It will return maximum size
resize : It will change size
capacity : It will return size of allocated storage capacity
empty : It will test if vector is empty
reserve : Request a change in capacity
shrink_to_fit :It will shrink to fit [C++11]
#include <iostream>
#include <vector>
using namespace std;

int main(void)
{
    std::vector<int> myvector;
    for (int i=1; i<=5; i++) 
        myvector.push_back(i);

    cout<<"Size of vector using .size is "<<myvector.size()<<endl;
    cout<<"Size of vector using .max_size is "<<myvector.max_size()<<endl;
    cout<<"Capacity of vector using .capacity is "<<myvector.capacity()<<endl;
    cout<<"Resize of vector using .resize is "<<endl;
    myvector.resize(100);
    cout<<"Capacity of vector after resize using .capacity is "<<myvector.capacity()<<endl;
    
}
Output:
Size of vector using .size is 5
Size of vector using .max_size is 4611686018427387903
Capacity of vector using .capacity is 8
Resize of vector using .resize is
Capacity of vector after resize using .capacity is 100
7. vector member function to access the elements.
———————————————————————————-
operator[] : Access element
at : Access element
front : Access first element
back : Access last element
data   : Access data [C++11]
#include <iostream>
#include <vector>
using namespace std;

int main(void)
{
    std::vector<int> myvector;
    for (int i=1; i<=5; i++) 
        myvector.push_back(i);

    std::vector<int>::size_type sz = myvector.size();
    std::cout << "myvector contains:";
    cout<<"Printing using operator[]"<<endl;
    for (unsigned i=0; i<sz; i++)
        std::cout << ' ' << myvector[i];
    std::cout << '\n';
   
    cout<<"Printing using at()"<<endl;
    for (unsigned i=0; i<sz; i++)
        std::cout << ' ' << myvector.at(i);
    std::cout << '\n'; 
    
    cout<<"The front of the vector using .front() = "<<myvector.front()<<endl;
    cout<<"The front of the vector using .back() = "<<myvector.back();
}
Output:
myvector contains:
Printing using operator[]
 1 2 3 4 5
Printing using at()
 1 2 3 4 5
The front of the vector using .front() = 1
The front of the vector using .back() = 5
8. vector member function to modify the elements.
———————————————————————————-
assign : Assign vector content
push_back : Add element at the end
pop_back : Delete last element
insert : Insert elements. This causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.
erase : Erase elements
swap : Swap content
clear : Clear content
emplace : Construct and insert element. The advantage of emplace over insert, it does in-place insertion and avoids an unnecessary copy of object. Reallocation happens only if there is a need of more space. The container size is increased by 1.
emplace_back : Construct and insert element at the end
#include <iostream>
#include <vector>
using namespace std;

int main(void)
{
    std::vector<int> myvector;
    for (int i=1; i<=5; i++) 
        myvector.push_back(i);

    std::vector<int>::size_type sz = myvector.size();
    std::cout << "myvector contains:"<<endl;
    for (unsigned i=0; i<sz; i++)
        std::cout << ' ' << myvector[i];
    std::cout << '\n';
    
    std::vector<int> myNewVector;
    for (int i=5; i<=10; i++) 
        myNewVector.push_back(i);
        
    std::cout << "myNewVector contains:"<<endl;
    for (unsigned i=0; i<sz; i++)
        std::cout << ' ' << myNewVector[i];
    std::cout << '\n';
    
    //swap operation
    myNewVector.swap(myvector);
    
    cout<<"****After swap****"<<endl;

    std::cout << "myvector contains:"<<endl;
    for (unsigned i=0; i<sz; i++)
        std::cout << ' ' << myvector[i];
    std::cout << '\n';

    std::cout << "myNewVector contains:"<<endl;
    for (unsigned i=0; i<sz; i++)
        std::cout << ' ' << myNewVector[i];
    std::cout << '\n';
}

9. How vector works internally?
———————————————————————————-

For example, if you have allocated memory for 10 vector variables, and when you insert 12th element, it will allocate bigger amount of memory in heap. Almost double than the previously allocated size.

Then it will copy all the elements from the previous location to new location.

Once the copy is completed, it will delete the previous allocated memory.

10. Do vector store in continuous memory or non continuous memory?
———————————————————————————-

Continuous memory location.

 

11. How to create 2D vector?
———————————————————————————-

2D vectors are also called as vector of vector.
Below is the syntax of 2D vector:

vector<vector<data_type>> vec;

Below is how you fill the elements:

vector<vector<int>> vec{ { 1, 2, 3 }, 
                         { 4, 5, 6 }, 
                         { 7, 8, 9, 4 } }; 

To use “push_back()” to insert elements into the array. For that you need to use another vector “v2”.

Step 1:

v2 = {1, 2, 3}
v1.push_back(v2);

Now the vector v1 will be ” v1 = { {1, 2, 3}, ”

Step 2:

v2 = {4, 5, 6}
v1.push_back(v2);

Now the vector v1 will be

" v1 = { {1, 2, 3}, "
	  {4, 5, 6}}"

12. How to remove elements in 2D vector?
———————————————————————————-

To remove elements, you need to use “.pop_back()”.

For example;

v = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }

v[2].pop_back()

v = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8 } }
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *