Reputation: 12341
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) );
}
Upvotes: 0
Views: 785
Reputation: 473322
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};
Upvotes: 3