STL: how to overload operator= for <vector>?
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.
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.
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 :)
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
}
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! ;)
}
精彩评论