What is Vector in C++? Get started in 5 minutes

C++ vector is a template class in the Standard Template Library (STL) that functions as a more refined array. Unlike arrays, vectors can resize themselves automatically when you insert or delete elements, so they’re great to use when working with const…


This content originally appeared on DEV Community and was authored by Erin Schaffer

C++ vector is a template class in the Standard Template Library (STL) that functions as a more refined array. Unlike arrays, vectors can resize themselves automatically when you insert or delete elements, so they’re great to use when working with constantly changing data. Using vectors in your C++ program enables you to store your data with more flexibility and efficiency. Today, we’ll dive deeper into C++ vectors and discuss benefits, functions, and initialization.

We’ll cover:

What is std::vector in C++?

C++ vectors (also known as std::vector) are sequence containers that represent arrays that can change in size. They’re used to work with dynamic data, and they use contiguous storage locations for their elements. You can efficiently access the elements using offsets on regular pointers. Internally, C++ vectors use dynamically allocated arrays to store their elements. The array may require reallocation so it can grow in size when new elements are inserted.

Vector containers may allocate additional storage space to accommodate for potential growth, so the container may have a larger capacity than what’s actually being stored inside of it. You can use libraries to apply different growth strategies to strike a balance between reallocations and memory usage, but reallocations should only happen at logarithmically growing intervals of size. This allows you to use amortized constant time complexity when inserting individual elements at the end of the vector.

Since C++ vectors perform automatic reallocation, they’re able to manage storage and grow dynamically in an efficient way. Although they consume more memory than arrays, their efficiency and flexibility make using vectors worthwhile.

Let’s discuss a few more benefits of C++ vector:

  • There’s no maximum size, which is helpful if you don’t know how big your data will be beforehand
  • Their resizing capabilities make it easier to handle dynamic elements
  • Since C++ vector is a template class, you don’t have to type in the same code to handle different data
  • Whenever the total amount of memory is used, automatic reallocation happens
  • You can easily copy and assign other vectors

C++ vector functions

There are many public member functions associated with C++ vectors. Let’s take a look at some of the functions and what they do.

  • cbegin: returns a const_iterator pointing to the first element in the container

Note: A const_iterator is an iterator that points to the const content. It can be increased and decreased like the iterator returned by vector::begin, but it can’t be used to modify the contents it points to.

  • cend: returns a const_iterator pointing to the past-the-end element in the container

  • crbegin: returns a const_reverse_iterator pointing to the last element in the container

  • crend: returns a const_reverse_iterator pointing to the theoretical element preceding the first element in the container

  • emplace_back: inserts a new element at the end of the vector, right after the current last element

  • max_size: returns the maximum size

  • pop_back: removes the last element in the vector

  • push_back: adds a new element at end of the vector

  • rbegin: returns a reverse iterator pointing to the last element in the vector

Note: Reverse iterators iterate backward. Increasing a reverse iterator moves it towards the beginning of the container.

  • rend: returns a reverse iterator pointing to the theoretical element preceding the first element in the vector

  • shrink_to_fit: requests the container to reduce its capacity to fit its size

  • std::vector::end: returns an iterator referring to the past-the-end element in the vector container

  • vector::capacity: returns the size of the storage space currently allocated for the vector

  • vector::front: returns a reference to the first element in the vector

  • vector::back: returns the last element of the vector

  • vector::size: returns the number of elements in the vector

Note: This returns the number of actual objects held in the vector, which isn’t necessarily equal to its storage capacity.

  • vector::begin: returns an iterator pointing to the first element in the vector

How to initialize a C++ vector

Now that we know more about the basics and some of the functions of C++ vectors, let’s discuss the initialization methods.

There are four ways to initialize a vector in C++:

1. Using an array

This method passes an array to the constructor of the vector class. The passed array contains the elements which will populate the vector.

#include <iostream>
#include <vector>
using namespace std;

int main() {

  vector<int> vec{1,2,3,4,5}; 

  for (int i = 0; i < vec.size(); i++)
  {
    cout << vec[i] << " "; 
  }
  return 0; 
}

Output: 1 2 3 4 5

2. Pushing the values one at a time

All the elements that need to populate a vector can be pushed, one at a time, into the vector using the vector class method push_back.

#include <iostream>
#include <vector>
using namespace std;

int main() {

  vector<int> vec;  

  vec.push_back(1); 
  vec.push_back(2); 
  vec.push_back(3);
  vec.push_back(4); 
  vec.push_back(5); 

  for (int i = 0; i < vec.size(); i++)
  {
    cout << vec[i] << " "; 
  }
  return 0; 
}

Output: 1 2 3 4 5

3. Using the overloaded constructor of the vector class

This method is mainly used when a vector needs to be populated with multiple elements of the same value (if a vector needs to be populated with ten 5’s, for example).

#include <iostream>
#include <vector>
using namespace std;

int main() {

  int num_of_ele = 10; 

  // the overloaded constructor takes the number of 
  // values and the value itself as parameters.
  vector<int> vec(num_of_ele, 1); 

  for (int i = 0; i < vec.size(); i++)
  {
    cout << vec[i] << " "; 
  }
  return 0; 
}

Output: 1 1 1 1 1 1 1 1 1 1

4. Using an already initialized vector

This method passes the begin() and end() iterators of an already initialized vector to a vector class constructor. A new vector is initialized and populated by the elements in the old vector.

#include <iostream>
#include <vector>
using namespace std;

int main() {

  vector<int> vec_1{1,2,3,4,5};

  vector<int> vec_2(vec_1.begin(), vec_1.end());

  for (int i = 0; i < vec_2.size(); i++)
  {
    cout << vec_2[i] << " "; 
  }
  return 0; 
}

Output: 1 2 3 4 5

What to learn next

Using C++ vectors in your program will allow you to store your data with more flexibility and efficiency. They’re an ideal tool to use when working with constantly changing data. Now that you know more about vectors, you’re ready to move into more C++ concepts.

Some recommended concepts to cover next are:

  • C++ Templates
  • Concurrency with Modern C++
  • Embedded programming in C++
  • Etc.

To get started learning about these concepts, check out Educative’s hands-on learning path C++ for Programmers.
In this learning path, you’ll dive deeper into C++ fundamentals, working your way from basic to advanced concepts. By the end, you’ll have enough C++ skills to confidently solve real-world problems and impress your interviewers.

Happy learning!

Continue reading about C++


This content originally appeared on DEV Community and was authored by Erin Schaffer


Print Share Comment Cite Upload Translate Updates
APA

Erin Schaffer | Sciencx (2021-05-14T18:48:37+00:00) What is Vector in C++? Get started in 5 minutes. Retrieved from https://www.scien.cx/2021/05/14/what-is-vector-in-c-get-started-in-5-minutes/

MLA
" » What is Vector in C++? Get started in 5 minutes." Erin Schaffer | Sciencx - Friday May 14, 2021, https://www.scien.cx/2021/05/14/what-is-vector-in-c-get-started-in-5-minutes/
HARVARD
Erin Schaffer | Sciencx Friday May 14, 2021 » What is Vector in C++? Get started in 5 minutes., viewed ,<https://www.scien.cx/2021/05/14/what-is-vector-in-c-get-started-in-5-minutes/>
VANCOUVER
Erin Schaffer | Sciencx - » What is Vector in C++? Get started in 5 minutes. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/05/14/what-is-vector-in-c-get-started-in-5-minutes/
CHICAGO
" » What is Vector in C++? Get started in 5 minutes." Erin Schaffer | Sciencx - Accessed . https://www.scien.cx/2021/05/14/what-is-vector-in-c-get-started-in-5-minutes/
IEEE
" » What is Vector in C++? Get started in 5 minutes." Erin Schaffer | Sciencx [Online]. Available: https://www.scien.cx/2021/05/14/what-is-vector-in-c-get-started-in-5-minutes/. [Accessed: ]
rf:citation
» What is Vector in C++? Get started in 5 minutes | Erin Schaffer | Sciencx | https://www.scien.cx/2021/05/14/what-is-vector-in-c-get-started-in-5-minutes/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.