c++ - 将自定义对象添加到 vector 时如何启用 move 语义?

标签 c++ c++11 move-semantics

下面的代码将包含大 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/

相关文章:

c++ - 正则表达式替换为 c++11 中的回调?

c++ - 了解 logb() 的工作原理

c++ - GMP - 在 mpz_t/mpz_class 中存储 64 位整数并取回 64 位整数

c++ - 如何返回带参数的 lambda 函数?

c++ - SFINAE:如果不带参数调用,则会出现不明确的重载

rust - 为什么调用 FnOnce 关闭是一个 Action ?

c++ - 编译器在不应该生成默认 move 构造函数时生成

c++ - 如何循环异构类的实例以调用具有相同名称和参数的方法?

c++ - 向 Boost unordered_map 添加一个元素

c++ - move 语义和完美转发的区别