DEV Community

Cover image for What is Vector in C++? Get started in 5 minutes
Erin Schaffer for Educative

Posted on • Originally published at educative.io

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 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; 
}
Enter fullscreen mode Exit fullscreen mode

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; 
}
Enter fullscreen mode Exit fullscreen mode

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; 
}
Enter fullscreen mode Exit fullscreen mode

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; 
}
Enter fullscreen mode Exit fullscreen mode

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++

Top comments (2)

Collapse
 
sandordargo profile image
Sandor Dargo

Nice summary. A few comments:

You can initialize a vector from an array, but that's not what happens at "1. Using an array".

If you want to show how to initialize a vector from an array, look at this example:

static const int arr[] = {16,2,77,29};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
Enter fullscreen mode Exit fullscreen mode

What happens in the example in this article is using the {}-initialization introduced by C++11 and that doesn't involve any arrays. Instead what you have on the right side is std::initializer_list and you use constructor #10 of vector: https://en.cppreference.com/w/cpp/container/vector/vector.

Sadly many articles on the net make the very same mistake (I guess one inspires the others).

Before I forget, vector does have a maximum size that's why there is max_size() that you also referenced.

Collapse
 
erineducative profile image
Erin Schaffer

Thank you for this information, Sandor! I appreciate it.