push_back():
#include <iostream>
#include<vector>
using namespace std;
int main()
{
int len = 10;
vector<int> lint;
for (int i = 0; i < len; ++i)
{
//lint.emplace_back();
lint.push_back(i);
}
for (int j = 0; j < len; ++j)
{
cout << lint[j]<<endl;
}
return 0;
}
0
1
2
3
4
5
6
7
8
9
emplace_back():
#include <iostream>
#include<vector>
#include<iomanip>
using namespace std;
int main()
{
int m = 4, n = 5;
vector<vector<int>> lint;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
lint.emplace_back();
//or
/*vector<int> temp;
lint.push_back(temp);*/
lint[i].push_back((i)*n+j);
}
}
for (int ii = 0; ii < m; ii++)
{
for (int jj = 0; jj < n; jj++)
{
cout <<setw(4)<<lint[ii][jj] << ' ' ;
}
cout << endl;
}
return 0;
}
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
如果直接使用push_back:
//lint.emplace_back();
/*vector<int> temp;
lint.push_back(temp);*/
lint.push_back();
lint[i].push_back((i)*n + j);
错误提示:
没有与参数列表匹配的 重载函数“std::vector<_Ty,Alloc>::push_back [其中 _Ty=<int, std::allocator<int>>,_Alloc=std::allocator<std::vector<int, std::allocator<int>>>]”实例对象是:std::vector<<std::vector<<int, std::allocator<int>>, std::allocator<std::vector<int::allocator<int>>>>