gpt4 book ai didi

c++ - vector.emplace_back() 和 vector.push_back() 做同样的事情吗?

转载 作者:可可西里 更新时间:2023-11-01 16:37:30 25 4
gpt4 key购买 nike

所以我试图将整数添加到我的 vector 的背面,并错误地认为 push_back() 将新数据添加到 vector 的前面(又名 vector[0])。我在 Xcode 中做了一个测试,并针对 emplace_back() 测试了 push_back() 并得到了相同的结果。我以为他们是不同的,但这让我觉得也许他们做同样的事情。如果是这样,为什么 vector 有不同的方法?

这是我的代码,以防我这样做:

#include <vector>
#include <iostream>

using namespace std ;

int main(int argc, const char * argv[])
{
// for push_back
vector<int> push;
push.push_back(1);
push.push_back(2);
push.push_back(3);
push.push_back(4);
push.push_back(5);
push.push_back(6);
//display push_back
for (int i = 0; i < push.size(); i++) {
cout << "push[" << i << "]: " << push[i] << endl;
}
// distance between the two funcitons
cout << endl << endl;

vector<int> emplace;
emplace.emplace_back(1);
emplace.emplace_back(2);
emplace.emplace_back(3);
emplace.emplace_back(4);
emplace.emplace_back(5);
emplace.emplace_back(6);

//display emplace_back
for (int i = 0; i < emplace.size(); i++) {
cout << "emplace[" << i << "]: " << emplace[i] << endl;
}
return 0;
}

返回是:

push[0]: 1
push[1]: 2
push[2]: 3
push[3]: 4
push[4]: 5
push[5]: 6


emplace[0]: 1
emplace[1]: 2
emplace[2]: 3
emplace[3]: 4
emplace[4]: 5
emplace[5]: 6

我知道这是一个 super 简单的问题,但我只是想确保我没有做一些愚蠢的错误并且误解了 vector 类的能力。

最佳答案

区别在于 emplace_back 将在原地构造对象,而不是复制或移动,cppreference section on std::vector::emplace_back说:

which typically uses placement-new to construct the element in-place at the location provided by the container. The arguments args... are forwarded to the constructor

这在重物的情况下很重要。我们可以看到这是来自 original proposal 的动机。其中说:

The motivation for placement insert is that containers—especially node-based containers—are very useful for the storage of heavy objects. In some environments efficiency is very important, but there is in general no way to put elements into containers without copying them. A heavy object may store its data directly, in which case move semantics will not improve copy performance. Furthermore, when efficiency is critical the solution cannot depend on compiler optimizations since they are optional and may not occur where they are most needed. Placement insertion lets us create an element once, in the container where we want it, and never have to move it or copy it. It does so in a simple and direct way by introducing new variadic functions that take arguments that are passed on to the element’s constructor using variadic templates and perfect forwarding.

我们可以举例说明这与 Effective Modern C++ 有什么不同吗? Item 42: Consider emplacement instead of insertion,有如下例子:

std::vector<std::string> vs; // container of std::string
vs.push_back("xyzzy"); // add string literal

这导致创建一个临时的,而不是:

vs.emplace_back("xyzzy");

没有。

关于c++ - vector.emplace_back() 和 vector.push_back() 做同样的事情吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28222736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com