c++ - 将自定义对象添加到向量时如何启用移动语义?
问题描述
下面的代码将包含大向量的对象传递给向量。我希望这是高性能的。我需要test
在调用中转换为右值push_back
吗?我需要告诉编译器如何移动 struct 的实例Test
吗?还是这一切都会自动进行?
int main()
{
struct Test
{
std::vector<size_t> vals;
double sum;
};
std::vector<Test> vecOfTest;
vecOfTest.reserve(100000);
for (size_t i = 0; i < 100000; i++)
{
Test test{};
test.vals.reserve(i);
for (size_t j = 0; j < i; j++)
{
test.vals.push_back(j);
test.sum += j;
}
vecOfTest.push_back(test);
}
return 0;
}
解决方案
我希望这是高性能的
以下应该足够好。我希望评论能帮助你理解代码。
#include <vector>
#include <iostream>
#include <numeric>
struct Test
{
std::vector<size_t> vals;
double sum = 0; // initialing is a good idea
Test(const size_t v, const double res) // provide constructor(appropriate one)
: vals(v), // tell the size of the vals directly in the constructor
sum(res)
{}
};
int main()
{
std::vector<Test> vecOfTest;
vecOfTest.reserve(100000);
for (size_t i = 0; i < 100000; i++)
{
// Test& last_test = vecOfTest.emplace_back() needs C++17, otherwise
// use std::vector::back()
auto& last_test = vecOfTest.emplace_back( // create the Test object in place and take the reference to it
i, // tell the size of vals in newly creating Test object
((i - 1) * i) / 2.0 // ((j-1) * j)/2 = sum from 0 to j-1
);
std::iota(std::begin(last_test.vals), std::end(last_test.vals), static_cast<size_t>(0)); // populate, 0 to size of vals
}
return 0;
}
推荐阅读
- hl7-v2 - 将最后一组代码添加到患者记录后,ADT 消息如何变化?
- javascript - 在 jQuery 调用中排序
- c - free()-ing 一个 char* 在 sscanf()" 之后停止工作?
- python - OpenCV 错误: cvtColor 中的断言失败 ((scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F))
- c# - C# - 如何通过选中复选框以编程方式创建文本框?
- react-native - 如何在本机反应中设置形状(ART)区域的点击事件?
- android-studio - in.something.somethingelse 在 kotlin 中不是有效的包名吗?
- c - Eclipse:我可以运行一个程序,但我无法调试它
- solr - Solr - 如何突出显示特定领域的特定术语
- python - 为什么我的 webhook 没有向我的对话流代理发送响应