Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

Vectors in C++: An Ultimate Guide

Basics of Python
Basics of Python
icon
5 Hrs. duration
icon
9 Modules
icon
1800+ Learners
logo
Start Learning

Vectors are quite similar to dynamic arrays. Their effect is that when a new entity is added or removed from the list, the vector has an automatic resizing feature and is, therefore, much more versatile than a static list.  Vectors also contain an array of member functions for replacing, deleting, and Getting specific elements, which further enhances the quality of the dynamic data structure.

 

What is std:: vector in C++?

 

The std:: vector in C++ is a part of the Standard Template  Library(STL) and represents a dynamic array that can grow and shrink in size. It is a highly useful and versatile container, providing features similar to arrays but with the added benefits of dynamic resizing and a rich set of functions for easy manipulation. This is defined inside the <vector> header file. The member functions of the std:: vector class provide various functionalities to vector containers.

Characteristics of Vectors

 

  • Dynamic Sizing: Unlike arrays, vectors can automatically adjust their size, growing or shrinking as needed during runtime.
  • Contiguous Memory: Like arrays, vectors store elements in contiguous memory locations, allowing efficient random access using the subscript operator ([]).
  • Automatic Memory Management: The std::vector manages its own memory. It automatically allocates more memory when needed, thus abstracting the complexities of manual management.
  • Rich Set of Functions: Vectors provide many useful methods such as push_back(), pop_back() , insert(), erase(), size() and capacity().

Syntax for Declaring a Vector

#include <vector> std::vector<int> myVector;

Where the data type is the type of data for each element of the vector, we can remove the std:: if you have already used the std namespace.

Initialization of Vector in C++

 

There are many ways to initialize a vector in C++ language.

 

  • Initialization Using List: The initialization is done with a declaration. Pass the elements to the vector constructor to create a vector with the specified elements.

 

vector <dataType> name ({value1, value2, value3 ….}) ;

 

  • Initialization with a single value: We can also initialize with declaration. Here, we specify the size of the vector and then initialize every element of the vector with the value.

 

vector <dataType> name(size, value) ;

 

  • Initialization from Another Vector

 

We can also create a vector that is an exact copy of another vector.

 

vector<dataType> name (other_vec) ;

Commonly Used Member Function

Some commonly used member functions of std:: vector class are written below.

 

Iterators

 

  • begin(): It returns an iterator pointing to the first element in the vector.
  • endO(): It returns an iterator pointing to the theoretical element that follows the last element in the vector.
  • rbegin(): This returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from the last to the first element.
  • rend(): This function reverses an iterator that points to the theoretical element preceding the first element in the vector (considered as the reverse end).
  • cbegin(): This function returns a constant iterator pointing to the first element in the vector.
  • cend(): This function returns a constant iterator that points to the theoretical element that follows the last element in the vector.
  • crbegin(): This returns a constant reverse iterator pointing to the last element in the vector reverse beginning. This moves from the last to the first element.
  • crend(): This function returns a constant reverse iterator pointing to the theoretical element preceding the first element in the vector.

 

Program

// C++ program to illustrate the

// iterators in vector

#include <iostream> #include <vector> using namespace std; int main() { vector<int> g1; for (int i = 1; i <= 5; i++) g1.push_back(i); cout << "Output of begin and end: "; for (auto i = g1.begin(); i != g1.end(); ++i) cout << *i << " "; cout << "nOutput of cbegin and cend: "; for (auto i = g1.cbegin(); i != g1.cend(); ++i) cout << *i << " "; cout << "nOutput of rbegin and rend: "; for (auto ir = g1.rbegin(); ir != g1.rend(); ++ir) cout << *ir << " "; cout << "nOutput of crbegin and crend : "; for (auto ir = g1.crbegin(); ir != g1.crend(); ++ir) cout << *ir << " "; return 0; }

Output

Output of begin and end: 1 2 3 4 5 Output of cbegin and cend: 1 2 3 4 5 Output of rbegin and rend: 5 4 3 2 1 Output of crbegin and crend : 5 4 3 2 1

Capacity

 

  • size(): This function returns the number of elements in the vector.
  • max_size(): This function returns the maximum number of elements the vector can hold.
  • size(): The returns the number of elements in the vector.
  • capacity(): This returns the size of the storage space currently
  • rsize(n): This resizes the container to contain ‘n’ elements.
  • Empty (): This returns whether the container is empty.
  • shrink_to_fit(): This function reduces the capacity of the container to fit its size and destroys all elements beyond the capacity.
  • reserve(): This function requests that the vector capacity be at least enough to contain n elements.

 

Program

// C++ program to illustrate the

// capacity function in vector

#include <iostream> #include <vector> using namespace std; int main() { vector<int> ob; for (int i = 1; i <= 5; i++) ob.push_back(i); cout << "Size : " << ob.size(); cout << "nCapacity : " << ob.capacity(); cout << "nMax_Size : " << ob.max_size(); ob.resize(4); cout << "nSize : " << ob.size(); if (ob.empty() == false) cout << "nVector is not empty"; else cout << "nVector is empty"; ob.shrink_to_fit(); cout << "nVector elements are: "; for (auto it = ob.begin(); it != ob.end(); it++) cout << *it << " "; return 0; }

Output

Size : 5 Capacity : 8 Max_Size : 2305843009213693951 Size : 4 Vector is not empty Vector elements are: 1 2 3 4

Element Access

  • Reference_operator[g] : This returns a reference to the element at position ‘g’ in the vector.
  • at(g): This returns a reference to the element at position ‘g’ in the vector.
  • front(): This returns a reference to the first element in the vector.
  • back(): This returns a reference to the last element in the vector
  • data(): This function returns a direct pointer to the memory array used internally by the vector to store its owned elements.

 

Program

// C++ program to illustrate the

// element access in vector

#include <bits/stdc++.h> using namespace std; int main() { vector<int> ob2; for (int i = 1; i <= 10; i++) ob2.push_back(i * 10); cout << "nReference operator [g] : ob[2] = " << ob2[2]; cout << "nat : ob2.at(4) = " << ob2.at(4); cout << "nfront() : ob2.front() = " << ob2.front(); cout << "nback() : ob2.back() = " << ob2.back(); // pointer to the first element int* pos = ob2.data(); cout << "nThe first element is " << *pos; return 0; }

Output

Reference operator [g] : ob[2] = 30 at : ob2.at(4) = 50 front() : ob2.front() = 10 back() : ob2.back() = 100 The first element is 10

Modifiers

  • assign(): This function assigns a new value to the vector elements by replacing old ones.
  • push_back(): This pushes the elements into a vector from the back.
  • pop_back(): It is used to pop or remove elements from a vector from the back.
  • insert(): This inserts new elements before the element at the specified position.
  • erase(): It removes elements from a container from the specified position or range.
  • swap(): This is used to swap the contents of one vector with another vector of the same type. Size may differ.
  • clear(): This is used to remove all the elements of the vector container.
  • emplace(): This extends the container by inserting a new element at the position.
  • emplace_back(): This inserts a new element into the vector container. The new element is added to the end of the vector.

 

Program

#include <bits/stdc++.h> #include <vector> using namespace std; int main() { vector<int> v; v.assign(5, 10); cout << "The vector elements are: "; for (int i = 0; i < v.size(); i++) cout << v[i] << " "; v.push_back(15); int n = v.size(); cout << "nThe last element is: " << v[n - 1]; v.pop_back(); cout << "nThe vector elements are: "; for (int i = 0; i < v.size(); i++) cout << v[i] << " "; v.insert(v.begin(), 5); cout << "nThe first element is: " << v[0]; v.erase(v.begin()); cout << "nThe first element is: " << v[0]; v.emplace(v.begin(), 5); cout << "nThe first element is: " << v[0]; v.emplace_back(20); n = v.size(); cout << "nThe last element is: " << v[n - 1]; v.clear(); cout << "nVector size after clear(): " << v.size(); vector<int> v1, v2; v1.push_back(1); v1.push_back(2); v2.push_back(3); v2.push_back(4); cout << "nnVector 1: "; for (int i = 0; i < v1.size(); i++) cout << v1[i] << " "; cout << "nVector 2: "; for (int i = 0; i < v2.size(); i++) cout << v2[i] << " "; v1.swap(v2); cout << "nAfter Swap nVector 1: "; for (int i = 0; i < v1.size(); i++) cout << v1[i] << " "; cout << "nVector 2: "; for (int i = 0; i < v2.size(); i++) cout << v2[i] << " "; }

Output

The vector elements are: 10 10 10 10 10 The last element is: 15 The vector elements are: 10 10 10 10 10 The first element is: 5 The first element is: 10 The first element is: 5 The last element is: 20 Vector size after clear(): 0 Vector 1: 1 2 Vector 2: 3 4 After Swap Vector 1: 3 4 Vector 2: 1 2
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Time Complexity Considerations

Let’s see the various time complexity operations on vectors.

 

  • Random access: constant O(1).
  • Insertion or removal: constant O(1)
  • Knowing the size: constant O(1)
  • Resizing the vector: Linear O(N).

Conclusion

Vectors in C++ are another effective tool in the arsenal of the programmer which help to reduce the amount of effort in working with dynamic arrays. It gives many advantages like freeing an application from the need to manage memory on its own, the ability to expand and shrink the list’s size, and several functions to add, remove, and search for an element.

 

As you will see, vectors help developers to write more elegant and efficient code because memory needs to be managed less manually or with explicit programs to do so. Vectors will be useful when coding and help bring out the best in your programming and source code. Learn how vectors can be so useful and flexible in C++.

FAQs
A vector is a dynamic array that can change size automatically.
If you increase the size, new elements are default-initialized. If you decrease the size, elements are removed from the end of the vector.
Vectors are not thread-safe by default. If multiple threads modify a vector, you should use synchronization mechanisms to avoid data races.
For built-in types, new elements are initialized to zero. For user-defined types, the default constructor is called.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

19 October, 12:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.

Data Science

Accelerator Program in Business Analytics & Data Science

Integrated Program in Data Science, AI and ML

Accelerator Program in AI and Machine Learning

Advanced Certification Program in Data Science & Analytics

Technology

Certificate Program in Full Stack Development with Specialization for Web and Mobile

Certificate Program in DevOps and Cloud Engineering

Certificate Program in Application Development

Certificate Program in Cybersecurity Essentials & Risk Assessment

Finance

Integrated Program in Finance and Financial Technologies

Certificate Program in Financial Analysis, Valuation and Risk Management

Management

Certificate Program in Strategic Management and Business Essentials

Executive Program in Product Management

Certificate Program in Product Management

Certificate Program in Technology-enabled Sales

Future Tech

Certificate Program in Gaming & Esports

Certificate Program in Extended Reality (VR+AR)

Professional Diploma in UX Design

Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

© 2024 Hero Vired. All rights reserved