简体   繁体   English

如何有效地使用emplace_back(对)?

[英]how to emplace_back(pair) efficiently?

I have 我有

using namespace std;   // for convenience in SO question only
vector<pair<array<int,3>, int>> foo;

and want to emplace_back an element with pair::first holding {i,j,k} and pair::second holding q . 并希望emplace_back一个元素与pair::first holding {i,j,k}pair::second holding q The only way I could get this compiling was with the rather clumsy 我能得到这个编译的唯一方法是相当笨拙

foo.emplace_back(piecewise_construct,
                 forward_as_tuple(i,j,k),
                 forward_as_tuple(q));

Is this efficient (ie is it guaranteed that the tuple s will be optimised away)? 这是否有效(即保证 tuple s将被优化掉)? Or is there another way that is guaranteed efficient? 还是有另一种保证有效的方法吗?

(I tried (我试过了

foo.emplace_back(std::initializer_list<int>{i,j,k}, q);

but to no avail with gcc 4.8.1). 但无法用gcc 4.8.1)。 I know that I can avoid this problem by defining 我知道我可以通过定义来避免这个问题

struct element : std::pair<std::array<int,3>,int>
{
  element(int i, int j, int k, int q)
  { first={i,j,k}; second=q; }
};

vector<element> foo;
foo.emplace_back(i,j,k,q);

but I'd prefer to do without such extra code. 但我宁愿没有这样的额外代码。

std::array<T, N> doesn't have any constructor taking a std::initializer_list<U> for any U , not even for U = T . std::array<T, N>没有任何构造std::initializer_list<U>为任何U获取std::initializer_list<U> ,甚至U = T Don't mistake the fact that it can be initialised from a braced-init-list for the presence of such a constructor. 不要误以为它可以从braced-init-list初始化,以确定是否存在这样的构造函数。

Instead, actually create an array. 相反,实际上创建一个数组。

foo.emplace_back(std::array<int,3>{i,j,k}, q);

There are hardly any guarantees about efficiency, and this is not guaranteed to be more efficient than your tuple approach. 几乎没有任何关于效率的保证,这并不能保证比你的元组方法更有效。 In practice, it shouldn't make much of a difference, I expect implementations to optimise both forms of emplace_back to the same machine code. 在实践中,它应该没有多大区别,我希望实现能够将两种形式的emplace_back优化为相同的机器代码。 If you really care, and you doubt that, measure it. 如果你真的关心,而你怀疑,那么衡量它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM