Ads by ProfitSence

C++ Adding and Accessing elements to a vector

Last Updated on Wednesday 5th Oct 2022

Adding elements to a vector


push_back adds a new element to the end of the vector.

					vector<string> students; // declare an empty vector

students.push_back("alice"); // add an element
students.push_back("adam"); // add another - now has size of 2 with elements: "alice", "adam"


C++ Add to Vector

push_back is a very common way to add elements and is useful when adding elements one at a time.


resize allocates memory for the desired number of elements in the vector and adjusts its size accordingly.

					vector<int> nums; // declare the vector

nums.resize(100); // allocate space for 100 ints in vector

for(int i = 0; i < nums.size(); i++){
  nums[i] = i; // set value using index


When adding many elements at the same time, using resize may be faster than push_back.

This is because when a new element is added to the end of a vector there might not be enough space in memory at the current location.


assign can be used to create a vector of a given size and populate it with uniform values, or to copy part of an existing vector. It reinitializes the vector deleting any previous elements.

					vector<float> vals; // declare the vector
vals.assign(100,0.0f); // add 100 floats all with value of 0.0

vector<Particle> num;

vector<Particle> copyParticles;
copyParticles.assign( num.begin(), num.begin()+5);


Accessing elements of a vector

operator []

Elements can be accessed using the [] operator with an index in the same style as c arrays.

					cout << names[0] << end; // !if there is no element 0, you have a memory access error

for( int i = 0; i < names.size(); i++){
   cout << names[i] << endl;



Vectors have a function at() that will return the value in the same way as the [] operator.

					cout << << endl;


This can make it useful for debugging, however for clarity and speed [] is usually preferred.