如何简单地分配不同结构的向量

How to simple assign vectors of different structs?

本文关键字:结构 向量 分配 何简单 简单      更新时间:2023-10-16

所以我有两个不同的结构(a和b)具有相同的变量,并且在结构b中有一个重载=运算符,用于将a转换为b。

我希望能够简单地将 a 的向量分配给向量 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;
}

问题是你的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++标准说我们不应该以下划线"_"开头的变量名称。

尽管ab看起来相同,编译器将它们视为不同的类型,即使a可转换为b(反之亦然)。因此,vector<a>vector<b> 是完全不相关的,因此您不能将一个分配给另一个,并且整个赋值无法编译。

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

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