In C++, the push_back()
function is used to add elements to the end of a dynamic array or vector. When working with a 2D vector, you can use push_back()
to add rows and then use push_back()
within each row to add elements to that row. Here's an example:
#include <iostream> #include <vector> int main() { // Declare a 2D vector std::vector<std::vector<int>> my2DVector; // Create the first row std::vector<int> row1; row1.push_back(1); row1.push_back(2); row1.push_back(3); // Create the second row std::vector<int> row2; row2.push_back(4); row2.push_back(5); row2.push_back(6); // Add rows to the 2D vector my2DVector.push_back(row1); my2DVector.push_back(row2); // Access and print elements of the 2D vector for (size_t i = 0; i < my2DVector.size(); ++i) { for (size_t j = 0; j < my2DVector[i].size(); ++j) { std::cout << my2DVector[i][j] << " "; } std::cout << std::endl; } return 0; }
In this example, row1
and row2
are two vectors representing two rows of a 2D vector. The push_back()
function is used to add elements to each row. Then, these rows are added to the my2DVector
using push_back()
.
You can continue to use this approach to add more rows or elements to the 2D vector as needed. Adjust the data types and values according to your specific requirements.