views:

294

answers:

4

There's 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
}

The thing I need to know is how to overload operator = so that I could make assignment like this:

vector<double> = vector<int>;

I've just tried a lot of ways, but always compiler has been returning errors...

Is there any option to make this code work without changing it? I can write some additional lines, but can't edit or delete the existing ones. Ty.

+2  A: 

You can't. The assignment operator must be a member function, which means it must be a member of the std::vector template which you are not allowed to modify (or so the C++ Standard says). So instead, write a free function:

void Assign( vector <double> & vd, const vector <int> & vi ) {
  // your stuff here
}
anon
Interesting downvote there - I don't suppose you would care to say why?
anon
+1: to make it equal :P
Kornel Kisielewicz
@Kornel Thanks :-) - most of the time I ignore downvotes, but occasionally I think their is a chance that the downvoter has a technical point they are too shy to elucidate - I suppose I should know better by now.
anon
+11  A: 

Why not do it in a easier way:

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

Or:

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

Both are supported out of the box :)

Kornel Kisielewicz
@David, I know, but they're probably the most elegant solution in the STL mindset.
Kornel Kisielewicz
(I deleted the comment by mistake) I know and I agree that this is the best solution. Any other solution will end up either calling this one internally or else reimplementing the internal details of the assign.
David Rodríguez - dribeas
A: 

OK, I see. I'll ask You in another way.. Is there any option to make this code work without changing it? I can write some additional lines, but can't edit or delete the existing ones. Ty.

MBes
See Neil's answer -- no you can't, unless you create a new class that inherits from std::vector -- and that is against the C++ standard.
Kornel Kisielewicz
You should have asked this supplemental by editing your original question. But to answer it - no the two vectors are of different types and cannot be assigned using vector <double>'s assignment operator.
anon
is this homework or a real question?
Idan K
@Kornel You certainly can inherit from a vector type - that isn't what I said, and wouldn't solve the problem anyway.
anon
@Idan KI've got an exam tomorrow and I'm just solving examples from previous year. It's highly possible that it's just a mistake...
MBes
very well, check my answer then
Idan K
A: 

If it's a puzzle, this 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! ;)
}
Idan K