c++ - 将元素从 std::vector<T1> move 到 std::vector<std::pair<T1,T2>>

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

将 std::move 元素从某种类型的 vector (T1) move 到相同类型 (T1) 和另一种类型 (T2) 的 std::pair 的 vector 中的最正确和最有效的方法是什么?

也就是说,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;
}

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

最佳答案

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

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

关于c++ - 将元素从 std::vector<T1> move 到 std::vector<std::pair<T1,T2>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40253189/

相关文章:

c++ - 如何使用 C++11 move 语义来显式避免复制

rust - Rust 中的 move 语义是什么?

c++ - 使用 XCode 调试器跟踪递归函数

c++ - 跨网络发送数据最快的 C/C++ 技术?

c++ - 内联静态成员变量

c++ - 线程之间通过共享 vector 进行通信

c++ - 从 C++11 中的函数调用返回 std::vector 的正确方法( move 语义)

只调用一次的 C++ 函数

c++ - 创建一个 vector 作为函数调用参数

c++ - 有没有办法做到这一点?