在 C++ 中从成对向量转换为两个独立向量的最快方法 [英] Fastest way to convert from vector of pairs to two independent vectors in C++

查看:41
本文介绍了在 C++ 中从成对向量转换为两个独立向量的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 pairvector.现在我想提取 pair.firstpair.second 作为独立向量.我可以迭代向量并这样做,但有更好/更快的方法吗?

解决方案

在 C++11 中,如果你不再需要旧的向量,你也许可以从移动语义中获得一点额外的效率:

>

for (auto it = std::make_move_iterator(v.begin()),end = std::make_move_iterator(v.end());它!=结束;++它){v1.push_back(std::move(it->first));v2.push_back(std::move(it->second));}

除此之外,您当然不能比一个循环做得更好.您必须至少接触每个元素一次,因此这是最有效的.

请注意,只有当元素类型本身具有比复制更好的移动语义时,移动才会有所作为.int 或任何 POD 都不是这种情况.但是,编写通用代码并没有什么坏处,这样您就可以在未来的情况下利用这一点.

如果复制/移动是一个问题,那么您应该考虑是否为原始向量使用一些视图适配器可能是更好的方法.

lets say I have a vector of pair<int,int>. Now I want to extract the pair.first and pair.second as independent vectors. I can iterate on the vector and do that but is there a better/faster way?

解决方案

In C++11, if you don't need the old vector anymore, you could perhaps get a tiny bit of extra efficiency from move semantics:

for (auto it = std::make_move_iterator(v.begin()),
         end = std::make_move_iterator(v.end()); it != end; ++it)
{
    v1.push_back(std::move(it->first));
    v2.push_back(std::move(it->second));
}

Other than that, you certainly cannot do better than one loop. You will have to touch every element at least once, so this is as efficient as it gets.

Note that moving can only make a difference if the element types themselves have move semantics that are better than copying. This is not the case for ints, or any PODs. But it can't hurt to write your code generically so that you can take advantage of this in future situations.

If copying/moving is a problem, though, you should consider whether some view adapter for your original vector might be a better approach.

这篇关于在 C++ 中从成对向量转换为两个独立向量的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆