In this article we will discuss how to add element in a vector.
std::vector provides a member function to push an element at the end i.e.
void push_back (const value_type& val);
It will push the element in the end of list. As, this function adds the element, so it also increases the size of vector by 1.
Check out following example of push_back with a vector of strings i.e.
#include <iostream> #include <vector> #include <string> int main() { // Creating a vector of int; std::vector<std::string> vecOfStr; std::cout << "Size of Vector = " << vecOfStr.size() << std::endl; // Push an element in vector, it will be appended in the last vecOfStr.push_back("AAA"); vecOfStr.push_back("BBB"); vecOfStr.push_back("BBB"); std::cout << "Size of Vector = " << vecOfStr.size() << std::endl; // Now lets print the content of vector, for (std::string data : vecOfStr) std::cout << data << std::endl; return 0; }
Output:
Size of Vector = 0 Size of Vector = 3 AAA BBB BBB
The above code uses the c++11’s newly introduced for loop. To compile the above code use following command,
g++ --std=c++11 example.cpp
Do you want to Learn Modern C++ from best?
We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.
Check Detailed Reviews of Best Modern C++ Courses
Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.