I want to copy std::vector<int>to another std::vector<myStruct>with an assignment operator in which it myStructcan be assigned int. So I wrote this piece of code:
#include <vector>
#include <iostream>
using namespace std;
struct myStruct
{
myStruct(int& a) : _val(a) { }
myStruct(int&& a) : _val(a) { }
myStruct& operator=(int& a)
{
_val = a;
return *this;
}
int _val;
};
int main()
{
vector<int> ivec;
ivec.push_back(1);
vector<myStruct> svec = ivec;
return 0;
}
And he gives me an error, because he cannot find the correct conversion between std::vector<myStruct>and std::vector<int>, although intit can be implicitly converted to myStruct. On the other hand, assigning an operator cannot be declared outside the class, so I conclude that manually writing an operator is not an option. So what should I do in this situation?
*** UPDATE: As Blastfurnaceothers have said this can be resolved using this code instead of assignment:
vector<myStruct> svec(ivec.begin(), ivec.end());
, , std::vector<myStruct> svec = someFunction(), someFunction std::vector<int>. ?