将元素从std :: vector <t1>移动到std :: vector <std :: pair <t1,t2>&gt;

时间:2016-10-26 03:25:27

标签: c++ vector move-semantics universal-reference

将std :: move元素从某个类型(T1)的向量移动到同一类型(T1)和另一个类型(T2)的std ::对向量中,最正确有效的方法是什么?

换句话说,我该如何编写MoveItems()?

#include <iostream> // For std::string
#include <string>   // For std::string
#include <vector>   // For std::vector
#include <utility>  // For std::pair

using std::vector;
using std::string;
using std::pair;

vector<string> DownloadedItems;
vector<pair<string,bool>> ActiveItems;

vector<string> Download()
{
    vector<string> Items {"These","Words","Are","Usually","Downloaded"};
    return Items;
}

void MoveItems()
{
    for ( size_t i = 0; i < DownloadedItems.size(); ++i )
        ActiveItems.push_back( std::pair<string,bool>(DownloadedItems.at(i),true) );
}

int main()
{
    DownloadedItems = Download();
    MoveItems();
    return 0;
}

感谢您的时间和帮助,我真的很感激!

2 个答案:

答案 0 :(得分:0)

你可以做的一些事情:

MoveItems()开始时,请致电ActiveItems.reserve(DownloadedItems.size());。这会阻止您的数组在将内容放入其中时调整大小。

而不是致电push_back致电emplace_backHere解释了这样做的好处。

值得注意的是,在这个例子中,您可以通过从一开始就构建std::pair而不是复制数据来停止复制到新的数据结构。

答案 1 :(得分:0)

void MoveItems()
{
    ActiveItems.reserve(DownloadedItems.size());
    for (auto& str : DownloadedItems)
        ActiveItems.emplace_back(std::move(str), true);
}

N.B。:对于与示例中的字符串一样小的字符串,由于SSO,移动可能与复制的成本相同,或者如果实现决定清空源代码,则可能稍微贵一些。