Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automatic conversion between stl vectors

What I want is to copy an std::vector<int> to another std::vector<myStruct> with assignment operator in which myStruct can be assigned an 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 it gives me error as it cannot find a valid conversion between std::vector<myStruct> and std::vector<int> although int can implicitly be converted to myStruct. On the other hand, assign operator cannot be declared outside the class so I deduce writing an operator manually is not an option. So what should I do in this situation?

*** UPDATE: As Blastfurnace and others said this can be solved using this code instead of assignment:

vector<myStruct> svec(ivec.begin(), ivec.end());

But imagine the situation in which I want to write a library and want to handle this in the library itself so the user can just write std::vector<myStruct> svec = someFunction() in which someFunction returns std::vector<int>. Isn't there any solution for this?

like image 786
Sinapse Avatar asked Dec 24 '22 14:12

Sinapse


1 Answers

You could use the constructor overload that takes an iterator range:

vector<myStruct> svec(ivec.begin(), ivec.end());
like image 135
Blastfurnace Avatar answered Jan 17 '23 19:01

Blastfurnace