所以我有兩個不同的結構(a & b)具有相同的變量,並且在結構b中有一個overloaded =運算符將a轉換爲b。如何簡單分配不同結構的向量?
我希望能夠以簡單分配的一個向量b的向量,但是編譯器給我一個錯誤:
main.cpp|61|error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::vector<_Ty>' (or there is no acceptable conversion)|
我認爲我已經有重載=運算符,它只會遍歷向量a併爲每個實例使用=運算符。我將如何做到這一點?
下面是代碼:
#include <iostream>
#include <vector>
using namespace std;
struct a
{
int x, y;
a() {}
a(int _x, int _y)
{
x = _x;
y = _y;
}
};
struct b
{
int x, y;
b(){}
b(int _x, int _y)
{
x = _x;
y = _y;
}
b& operator=(const a& _a)
{
x = _a.x;
y = _a.y;
return *this;
}
};
int main()
{
a a_test(1,2);
std::vector<a> a_vec;
std::vector<b> b_vec;
for(int i = 0; i <10; i++)
{
a_vec.push_back(a_test);
}
/*
for(int i = 0; i<a_vec.size(); i++)
{
b_vec.push_back(a_vec[i]);
}
*/
b_vec = a_vec;
return 0;
}
'std :: copy'應該可以工作。你必須手動迭代該向量。 – twentylemon
這不會工作,'std :: vector'不能這樣做。你必須手動複製。 – stefan