在struct C ++中使用std :: swap和std :: vector

时间:2012-12-02 17:41:09

标签: c++ c++11

如何使用std :: swap将向量复制到结构中的向量?以下是我要做的事情的一个例子

#include<vector>

using namespace std;

struct test{
    vector<int> a;
    vector<int> b;
};

int main(){

    int data[] = { 1, 2, 3 };
    int data2[] = {3,4,5 };
std::vector<int> c( &data[0], &data[0]+sizeof(data)/sizeof(data[0]));
std::vector<int> d( &data2[0], &data2[0]+sizeof(data2)/sizeof(data2[0]));


    test A = test(swap(c) , swap(d) );



}

1 个答案:

答案 0 :(得分:3)

您无法交换构造函数或函数参数。你只能换成左值。这是C ++ 11引入移动语义的原因之一:允许用户明确地将对象移动到参数中等等。

所以你需要给test一个合适的构造函数并调用它,使用std::move将你的左值vector对象转换为右值引用。

struct test{
    test(vector<int> _a, vector<int> _b) : a(std::move(_a)), b(std::move(_b)) {}
    vector<int> a;
    vector<int> b;
};

...

test A{std::move(c), std::move(d)};

如果你真的想要复制这些向量,你可以这样做:

test A{c, d};
相关问题