2015-06-13 14 views
2

所以我有兩個不同的結構(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; 
} 
+0

'std :: copy'應該可以工作。你必須手動迭代該向量。 – twentylemon

+0

這不會工作,'std :: vector'不能這樣做。你必須手動複製。 – stefan

回答

1

的問題是,你的operator=僅適用於單個元素,而不是整個載體

您需要定義一個構造,一個A轉換成B。您可以使用std::vector::assign而不是std::vector::operator=

#include <iostream> 
#include <vector> 
using namespace std; 

struct A 
{ 
    int x, y; 
    A(): x(0), y(0) {} 
    A(int x, int y): x(x), y(y) {} 
}; 

struct B 
{ 
    int x, y; 
    B(): x(0), y(0) {} 
    B(int x, int y): x(x), y(y) {} 

    // need to construct B from A 
    B(const A& a): x(a.x), y(a.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); 
    } 

    // b_vec = a_vec; // not like this 
    b_vec.assign(a_vec.begin(), a_vec.end()); // like this 

    return 0; 
} 

注:我改變了一些你的名字,因爲C++標準說,我們不應該以下劃線「_」開頭的變量名。

1

即使ab看起來相同,則編譯器將其視爲不同類型的,即使a可轉化爲b(或反之亦然)。因此,vector<a>vector<b>是完全不相關的,因此您不能將其中一個指派給另一個,並且整個任務無法編譯。

您可以像使用std::copy的算法,

std::copy(a_vec.begin(), a_vec.end(), std::back_inserter(b_vec));