Automatic conversion of stl vectors

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>. ?

+4
3

std::vector< myStruct> convertVector( const std::vector< int> & other)
{
    return std::vector< myStruct> ( ivec.begin(), ivec.end() );
}

, ( , "" ).


:

, , , , , :

class IntVector: public std::vector<int>{
    public:
    //conversion operator (note a VERY BAD IDEA using this, may come in handy in few cases)
    operator myStructVector () { 
        return convertVector(*this); 
    }
}

class myStructVector: public std::vector< myStruct>{
    //....
};

:

int main()
{
    IntVector ivec;
    ivec.push_back(1);
    myStructVector svec = (myStructVector)ivec;

    return 0;
}

^^

+1

, :

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

You can use instead vector<myStruct> svec(ivec.begin(), ivec.end());.

You can also use std::copy(ivec.begin(), ivec.end(), std::back_inserter(svec));or svec.assign(ivec.begin(), ivec.end());, as it may be better if you assign several times, since it can reuse the container vector<myStruct>after it has been cleaned.

+4
source

Source: https://habr.com/ru/post/1608129/


All Articles