C++ push_back Guide: Usage & Examples
In C++, push_back() is a member function used to add new elements to the end of a container. It is commonly used to add elements to a container, such as adding new elements to a vector.
Here is an example of using the push_back() function to add elements to a vector:
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector;
// 添加元素到vector中
myVector.push_back(10);
myVector.push_back(20);
myVector.push_back(30);
// 打印vector中的元素
for (int i = 0; i < myVector.size(); i++) {
std::cout << myVector[i] << " ";
}
return 0;
}
In the example above, we first create an empty vector called myVector, then use the push_back() function to add three integer elements to the vector. Lastly, we iterate through the vector using a for loop and print its elements. The output will be 10 20 30.