Teaching Newbies since 2014

kauress

  • Home
  • Javascript ❤
    • JavaScript
    • Node.js
  • WebDev Tuts
  • screencasts
  • Resources
  • VR & AR
  • Contact
  • Github
  • Twitter
  • YouTube
  • RSS
  • C++
You are here: Home / C++ / Adding/pushing data to a vector in C++

January 9, 2020 by: Kauress

Adding/pushing data to a vector in C++

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 
File Streams in C++
Enumerated types (Enum) in C++

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2021 ·Kauress