Initialize a vector in C++ using various methods

There are different ways to set up a vector in C++. Initializing a vector in C++ is an easy process that can help simplify your code and make the program more organized. With careful thought about which method will work best for your situation, it’s easy to make the most of C++’s many options for working efficiently with vectors.

In C++, what is a Vector?

A vector is a container that holds a sequence of items of the same type in a single memory location, and the elements are stored in a sequence and can be accessed using iterators.
You can initialize vectors in C++ in many different ways:

Initializing a vector by sequentially pushing values

Initializing an empty vector creates an empty vector that can later be filled with elements using the push_back() or insert() member functions. The push_back method allows elements to be added to the back of the vector sequentially, making this process relatively simple.

Example Code

#include <iostream>

#include <vector>

using namespace std;

int main() {
  //create an empty vector and push the values one by one
  vector < int > Vec;
  Vec.push_back(50);
  Vec.push_back(100);
  Vec.push_back(150);
  // print the vector
  for (int i: Vec)
    cout << i << "\n";
  return 0;
}

Output

50
100
150

When to use this method

But pushing values one at a time can be useful if you don’t want to erase any data already there. Furthermore, it’s also possible to use an iterator and range-based loop with ‘push_back’ for more advanced needs.

Initializing a vector by Determining the size and starting all values at zero

To begin, you must select a size for the vector by specifying a non-negative integer value. Once done, you can initialize all elements in the vector to their default values, typically 0 or nullptr, but it can be anything.

Example Code

#include <iostream>

#include <vector>

using namespace std;

int main() {
  int vectSize = 5;
  // Specify a vector of 'vectSize' with same values as 30
  vector < int > vect(vectSize, 0);
  // printing all the vector values
  for (int i: vect)
    cout << i << "\n";
  return 0;
}

Output

0
0
0
0
0

When to use this method

By using this method, your code will have fewer repetitions when assigning individual values, and it can be easier to add new elements as needed. It is essential to ensure you are specifying the right size of a vector when initializing, as exceeding this size, later on, could lead to unpredictable results, which can cause errors.

Initializing a vector out of an array

By taking advantage of the vector’s built-in constructors, you must pass the array as parameters to create a vector instance. The resultant vector will have elements equal to each element of the array.

Example Code

#include <iostream>

#include <vector>

using namespace std;
int main() {
  // initialize an array
  int array[] = {
    0,
    50,
    100,
    150,
    200
  };
  int arraySize = sizeof(array) / sizeof(array[0]);
  // initialize a vector from an array.
  vector < int > vect(array, array + arraySize);
  // displaying vector values
  for (int i: vect)
    cout << i << "\n";
  return 0;
}

Output

0
50
100
150
200

When to use this method

You can use a vector instance with a source size smaller than the array size by specifying only the initial elements in the array. Therefore, if you need to build an efficient data collection structure in C++, initializing a vector from an array is something you need to keep in mind!

Initializing a vector in C++ like arrays

Initializing a vector in C++ is a great way to set the stage for working with and manipulating data: Initializing a vector with an initializer list. An initializer list is a list of values enclosed in curly braces { }. When initializing a vector with an initializer list, it will copy all the values in the list into the vector.

Example Code

#include <iostream>

#include <vector>

using namespace std;
int main() {

  // initialize a vector like an array.
  vector < int > vect {
    0,
    100,
    150,
    200,
    250
  };

  // displaying all the vector values
  for (int i: vect)
    cout << i << "\n";
  return 0;
}

Output

0
50
100
150
200

When to use this method

Like arrays, these vectors can store multiple elements of different types, such as ints and strings, which can be accessed through an index. However, one of the defining features of vectors is that they can grow and shrink according to the demands of your program. Unlike arrays, there is no need to pre-define their size as they can dynamically resize when needed. It makes them especially useful when you need clarification on how much data needs to be handled.

Initializing a vector from a different vector

Initializing a vector from another vector in C++ is quite easy and provides the programmer with an efficient way to duplicate elements. This is called copy initialization, and it creates a new vector containing all the original elements.

You must create the destination vector and use the vector’s constructor to assign values from the source vector. Once initialized, any existing elements in the destination vector are replaced, and new elements are added if needed.

Example Code

#include <iostream>

#include <vector>

using namespace std;
int main() {

  //initialize a vector from another vector.
  vector < int > vectOne {
    0,
    50,
    100,
    150,
    200
  };
  vector < int > vectSecond(vectOne.begin(), vectOne.end());

  // displaying all the vector values
  for (int i: vectSecond)
    cout << i << "\n";
  return 0;
}

Output

0
50
100
150
200

When to use this method

You can use Vector methods for more specific requirements, such as adding elements between existing ones or replacing them at once. It’s just a matter of knowing which works best for your situation.

Initializing each member of a vector a specific initial value

Initializing vectors in C++ can be quickly done with a single line of code. Assign the desired value to the constructor of a vector instance. It will promptly populate the vector with that same value for each element.

Example Code

#include <iostream>

#include <vector>

using namespace std;
int main() {
  // initializing a vector
  vector < int > vectOne(5);
  int vectData = 12;
  //setting all the vector elements with same values
  fill(vectOne.begin(), vectOne.end(), vectData);
  for (int i: vectOne)
    cout << i << "\n";
}

Output

12
12
12
12
12

When to use this method

This method makes creating a vector composed entirely of the same value easy and efficient. Alternatively, one can generate a vector of a predetermined size and then use for-loops or a range-based for loop to set each value to something specific. However, depending on your use case, you might find initializing vectors via the constructor much easier.

Why initializing a vector in C++ is advantageous

The advantages of initializing a vector in C++ are many and varied:

  • The user can set their size limit and number of elements in their vector without difficulty.
  • Having the ability to modify vectors easily leads to improved performance as they can be tailored to suit user needs depending on the application.
  • Another advantage is that creating a vector gives the programmer access to a range of useful built-in methods such as push_back(), pop_back(), operator[] etc., all of which help make programming simpler and more efficient.
  • Moreover, creating a vector allows for easier and more reliable memory management since objects stored within the vector can be created and destroyed along with the vector itself with no extra effort required from the programmer.

Also, Read

How To Select the Best Computer For Gaming

How to Choose the Best Smart TV