将 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/