Skip to main content
C++

Adding/pushing data to a vector in C++

By January 9, 2020No Comments
Adding data to a vector in C++ rephrased means “Push data/element into an array” in JavaScript. JavaScript uses the “push” method whereas C++ uses “push_back” In JavaScript you push an element into an array like so:
const myNums = [1,2,500];
myNums.push(900);
console.log(myNums)// console.log [1, 2, 500, 900]
The same way in C++ :
#include <vector>
#include <iostream>
using namespace std;

int main() {
    // Initial Vector
    vector<int> v {1, 2, 500};
        // Push 900 to the back of the vector "array"
    v.push_back(900);
    // Print the contents of the vector
    for (int i=0; i < v.size(); i++) {
     cout << v[i] << " ";
    }
   
}
   
// Prints out 1, 2, 500, 900 

Leave a Reply