# C++ STL如何使用verctor的vector？代码示例

2021年4月3日18:49:44 发表评论 1,422 次浏览

``vector<vector<data_type>> vec;``

``````vector<vector<int>> vec{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9, 4 } };
where vec is the vector of vectors with different
number of elements in different rows``````

``````vector_name.push_back(value)

where value refers to the element
to be added in the back of the vector``````

``````v2 = {1, 2, 3}
v1.push_back(v2);``````

``````v2 = {4, 5, 6}
v1.push_back(v2);``````

``````// C++ program to demonstrate insertion
// into a vector of vectors

#include <iostream>
#include <vector>
using namespace std;

// Defining the rows and columns of
// vector of vectors
#define ROW 4
#define COL 5

int main()
{
// Initializing the vector of vectors
vector<vector< int > > vec;

// Elements to insert in column
int num = 10;

// Inserting elements into vector
for ( int i = 0; i < ROW; i++) {
// Vector to store column elements
vector< int > v1;

for ( int j = 0; j < COL; j++) {
v1.push_back(num);
num += 5;
}

// Pushing back above 1D vector
// to create the 2D vector
vec.push_back(v1);
}

// Displaying the 2D vector
for ( int i = 0; i < vec.size(); i++) {
for ( int j = 0; j < vec[i].size(); j++)
cout << vec[i][j] << " " ;
cout << endl;
}
return 0;
}``````

``````10 15 20 25 30
35 40 45 50 55
60 65 70 75 80
85 90 95 100 105``````

``vector_name[row_position].pop_back()``

``v[2].pop_back()``

``v[1].pop_back()``

``````// C++ program to demonstrate removal
// from a vector of vectors

#include <iostream>
#include <vector>
using namespace std;

// Driver Method
int main()
{
// Initializing 2D vector "vect" with
// sample values
vector<vector< int > > vec{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

// Removing elements from the
// last row of the vector
vec[2].pop_back();
vec[1].pop_back();

// Displaying the 2D vector
for ( int i = 0; i < 3; i++) {
for (
auto it = vec[i].begin();
it != vec[i].end(); it++)
cout << *it << " " ;
cout << endl;
}
return 0;
}``````

``````1 2 3
4 5
7 8``````

``````for i in [0, n)
{
for (iterator it = v[i].begin();
it != v[i].end(); it++)
{
// Operations to be done
// For example to print
print(*it)
}
}``````

``````// C++ code to demonstrate traversal
// of a 2D vector

#include <iostream>
#include <vector>
using namespace std;

// Driver Method
int main()
{
// Initializing 2D vector "vect" with
// sample values
vector<vector< int > > vec{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

// Displaying the 2D vector
for ( int i = 0; i < 3; i++) {
for (
auto it = vec[i].begin();
it != vec[i].end(); it++)
cout << *it << " " ;
cout << endl;
}

return 0;
}``````

``````1 2 3
4 5 6
7 8 9``````