下面的代码将包含大 vector 的对象传递到一个 vector 中。我希望这是高性能的。我是否需要在对 push_back
的调用中将 test
转换为右值?我需要告诉编译器如何 move 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;
}
最佳答案
I want this to be performant
以下应该足够好了。我希望评论能帮助您理解代码。
#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;
}
关于c++ - 将自定义对象添加到 vector 时如何启用 move 语义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55965412/