STL: how to overload operator = for <vector>?

A simple example:

#include <vector>

int main() {
 vector<int> veci;
 vector<double> vecd;

 for(int i = 0;i<10;++i){
  veci.push_back(i);
  vecd.push_back(i);
 }
 vecd = veci; // <- THE PROBLEM
}

I need to know how to overload operator = so that I can do the following:

vector<double> = vector<int>;

I just tried many ways, but the compiler always returned errors ...

Is it possible to make this code without changing it? I can write some additional lines, but I cannot edit or delete existing ones. Ty.


OK, I see. I will ask you differently .. Is there a way to make this code without changing it? I can write some additional lines, but I cannot edit or delete existing ones. Ty.

+3
source share
3 answers

Why not make it simpler:

vector<double> vecd( veci.begin(), veci.end() );

Or:

vecd.assign( veci.begin(), veci.end() );

:)

+12

. -, , std::vector, (, ++ Standard). :

void Assign( vector <double> & vd, const vector <int> & vi ) {
  // your stuff here
}
+6

If this is a puzzle, it will work ...

#include <vector>

int main() 
{
    vector<int> veci;

    {
        vector<double> vecd;
    }

    vector<int> vecd;

    for (int i = 0; i < 10; ++i)
    {
        veci.push_back(i);
        vecd.push_back(i);
    }

    vecd = veci; // voila! ;)
}
0
source

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


All Articles