0

How can i use std::swap to copy a vector to a vector in an struct? Heres an example of what i'm tying to do

#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) );



}
pyCthon
  • 11,746
  • 20
  • 73
  • 135
  • 4
    First of all, you don't have a constructor. Secondly, `std::swap` takes two arguments, and `std::vector` has a specialized one. Also, in C++11, you can just do this to create a vector: `std::vector c {1, 2, 3};` – chris Dec 02 '12 at 17:42

1 Answers1

3

You can't swap into a constructor or function argument. You can only swap into an lvalue. This is one of the reasons why C++11 introduced move semantics to begin with: to allow the user to explicitly move objects into parameters and so forth.

So you would need to give test an appropriate constructor and call it, using std::move to convert your lvalue vector objects into rvalue references.

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)};

If you really want to copy the vectors, you would do this instead:

test A{c, d};
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • aren't the ctor parameters needed to be rrefs? This way it looks like they are constructed with moved vectors. i.e _a is constructed with a moved c, then a is constructed with a moved _a. – zahir Dec 02 '12 at 22:27
  • @zahir: Yes, that's exactly what it's doing. This way, [whether you get a move or a copy is entirely up to the user.](http://stackoverflow.com/questions/8114276/how-do-i-pass-a-unique-ptr-argument-to-a-constructor-or-a-function/8114913#8114913) If the user wants to copy, they pass an lvalue. If the user wants to move, they pass an rvalue. The best part is that you don't have to write two constructors. – Nicol Bolas Dec 02 '12 at 22:47