C++push_back与emplace_back区别—简单代码实现对比

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>>>>

参考:emplace_back() 和 push_back 的区别

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值