Java/J2EE and SOA (249 Blogs) Become a Certified Professional

What are Vectors in C++ ? All You Need to Know

Published on Aug 09,2019 17 Views

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

Vectors in C++ are sequence containers representing arrays that can change in size. They use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. Following Pointers will be covered in this article:

 

What are Vectors in C++ ?

In C++, arrays are used to store sequential data which are static in nature. Generally, arrays are non-dynamic/static, that is to say, they are of fixed size, however, C++ also allows us to store data in dynamic arrays which are known as vectors in C++.

Vectors can resize itself automatically when an element is inserted or deleted depending on the need of the task to be executed. It is not same in an array where only a given number of values can be stored under a single variable name.

vectors-in-c++

Vector elements are placed in adjacent storage so that they can be accessed and travel across using iterators. In vectors, data is inserted at the end of it. Inserting an element at the end takes differential time, as sometimes there may be a need of extending the vector. Removing the last element takes only constant time because no resizing occurs. Inserting and erasing at the beginning or in the middle of the vector is linear in time.

Syntax:

vector< object_type > variable_name;

Example:

#include <vector>
int main()
{
    std::vector<int> my_vector;
}

In the above example, a blank vector is being created. Vector is a dynamic array and, doesn’t needs size declaration.

 

Member Functions of Vectors in C++

Vector container in STL provides us with various useful functions.

  1. Modifiers
  2. Iterators
  3. Capacity

Modifiers

  1. push_back(): The function pushes the elements into a vector from the back. If the type of object passed as a parameter in the push_back() is not same as that of the vector an exception is thrown.

  2. assign(): It assigns a new value to the vector elements by replacing old ones.

  3. pop_back(): The pop_back() function is used to pop or remove elements from a vector from the back. It reduces the size of the vector by one element.

  4. insert(): This function inserts new elements before the element before the position pointed by the iterator. We can also pass a third argument count, that counts the number of times the element is to be inserted before the pointed position.

  5. erase(): erase() function is used to remove elements from a container from the sp

  6. ecified position or range. We can either pass the position of the specific elements needs need to remove or we can pass the starting point and endpoint of a range of elements. 

  7. swap(): swap() function is used to swap the contents of one vector with another vector of the same type. Sizes may differ.

  8. clear(): clear() function is used to remove all the elements of the vector container

 

Example:

// Modifiers in vector 
#include <bits/stdc++.h> 
#include <vector> 
using namespace std; 
  
int main() 
{ 
    // Assign vector 
    vector<int> vec; 
  
    // fill the array with 12 seven times 
    vec.assign(7, 12); 
  
    cout << "The vector elements are: "; 
    for (int i = 0; i < 7; i++) 
        cout << vec[i] << " "; 
  
    // inserts 24 to the last position 
    vec.push_back(24); 
    int s = vec.size(); 
    cout << "nThe last element is: " << vec[s - 1]; 

     // prints the vector 
    cout << "nThe vector elements after push back are: "; 
    for (int i = 0; i < vec.size(); i++) 
    cout << vec[i] << " "; 
  
    // removes last element 
    vec.pop_back(); 
  
    // prints the vector 
    cout << "nThe vector elements after pop_back are: "; 
    for (int i = 0; i < vec.size(); i++) 
        cout << vec[i] << " "; 
  
    // inserts 10 at the beginning 
    vec.insert(vec.begin(), 10); 
  
    cout << "nThe first element after insert command is: " << vec[0]; 
  
    // removes the first element 
    vec.erase(vec.begin()); 
  
    cout << "nThe first element after erase command is: " << vec[0]; 
  
    // inserts at the beginning 
    vec.emplace(vec.begin(), 5); 
    cout << "nThe first element emplace is: " << vec[0]; 
  
    // Inserts 20 at the end 
    vec.emplace_back(20); 
    s = vec.size(); 
    cout << "nThe last element after emplace_back is: " << vec[s - 1]; 
  
    // erases the vector 
    vec.clear(); 
    cout << "nVector size after clear(): " << vec.size(); 
  
    // two vector to perform swap 
    vector<int> obj1, obj2; 
    obj1.push_back(2); 
    obj1.push_back(4); 
    obj2.push_back(6); 
    obj2.push_back(8); 
  
    cout << "nnVector 1: "; 
    for (int i = 0; i < obj1.size(); i++) 
        cout << obj1[i] << " "; 
  
    cout << "nVector 2: "; 
    for (int i = 0; i < obj2.size(); i++) 
        cout << obj2[i] << " "; 
  
    // Swaps obj1 and obj2 
    obj1.swap(obj2); 
  
    cout << "nAfter Swap nVector 1: "; 
    for (int i = 0; i < obj1.size(); i++) 
        cout << obj1[i] << " "; 
  
    cout << "nVector 2: "; 
    for (int i = 0; i < obj2.size(); i++) 
        cout << obj2[i] << " "; 
}

Output:

modifiers-vectors-in-c++

We can see the use of various modifiers that we studied above.

 

Iterators

  1. begin(): This function returns an iterator pointing to the first element in the vector.

  2. end(): The end() function returns an iterator pointing to the last element in the vector.

Example:

#include <iostream> 
#include <vector> 
  
using namespace std; 
  
int main() 
{ 
    vector<int> vec1; 
  
    for (int i = 1; i <= 10; i++) 
        vec1.push_back(i); 
  
    cout << "Understanding begin() and end() function: " << endl; 
    for (auto i = vec1.begin(); i != vec1.end(); ++i) 
        cout << *i << " "; 

    return 0; 
}

Output:

iterators

In the above example, we can see the use of begin() and end() function. First, we define a vector vec1, we push back values in it from 1 to 10 using a for a loop. Then we print the values of our vectors using for loop, we use begin( ) and end( ) function to specify the start and endpoint of our for a loop.

 

Capacity

  1. size(): This function returns the number of elements in the vector.

  2. max_size(): The max_size() function returns the maximum number of elements that the vector can hold.

  3. capacity(): The capacity() function returns the size of the storage space currently allocated to the vector expressed as number of elements based on the memory allocated to the vector.

  4. resize(): This function resizes the container so that it contains ‘n’ elements. If the current size of the vector is greater than n then the back elements are removed from the vector and id the current size is smaller than n then extra elements are inserted at the back of the vector.

  5. empty(): Returns whether the container is empty, it return true if vector is empty else returns false.

 

Example:

#include <iostream> 
#include <vector> 
  
using namespace std; 
  
int main() 
{ 
    vector<int> vec1; 
  
    for (int i = 1; i <= 10; i++) 
        vec1.push_back(i); 
  
    cout << "Size of our vector: " << vec1.size(); 
    cout << "nCapacity of our vector: " << vec1.capacity(); 
    cout << "nMax_Size of our vector: " << vec1.max_size(); 
  
    // resizes the vector size to 4 
    vec1.resize(4); 
  
    // prints the vector size after resize() 
    cout << "nSize of our vector after resize: " << vec1.size(); 
  
    // checks if the vector is empty or not 
    if (vec1.empty() == false) 
        cout << "nVector is not empty"; 
    else
        cout << "nVector is empty"; 
  
    return 0; 
}

Output:

capacity-vectors-in-c++

We can see the working of the capacity functions as we discussed above.

 

With this, we come to an end of this Vectors in C++ article. I hope you got to know the different member functions of Vectors and the working of each one of them. I hope you got an idea of what exactly is a namespace in C++ and what are the different ways of defining it. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.

Comments
0 Comments

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.