如何简单地分配不同结构的向量
How to simple assign vectors of different structs?
所以我有两个不同的结构(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
的构造函数。
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++
标准说我们不应该以下划线"_"开头的变量名称。
尽管a
和b
看起来相同,编译器将它们视为不同的类型,即使a
可转换为b
(反之亦然)。因此,vector<a>
和 vector<b>
是完全不相关的,因此您不能将一个分配给另一个,并且整个赋值无法编译。
您可以使用像std::copy
这样的算法,
std::copy(a_vec.begin(), a_vec.end(), std::back_inserter(b_vec));
相关文章:
- 将结构向量排序为子组
- NLOHMANN 的 JSON 库将数组转换为结构向量
- 如何在 c++ 中创建结构向量的映射
- 带unique_ptr的结构向量
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 将信息输入到下面显示的结构向量中的正确语法/格式是什么
- C++对结构向量进行排序
- 在C++中对结构向量进行排序时出现问题
- 将结构向量保存到文件中,并从C++文件中读取结构向量
- 搜索并替换结构向量中的值
- 在结构向量中查找最接近的值
- 清除结构向量时会发生什么?
- 如何从 node-ffi 调用 c++ 中以结构向量作为参数的方法?
- 对结构向量进行两次排序
- 将一种数据类型的向量复制到同一数据类型的结构向量中的有效方法是什么
- 如何二进制搜索结构向量并在适当的索引处插入
- 结构向量中自定义结构函数的内存使用
- C++11-在结构向量中修改结构的成员
- 我正在尝试找到一个特定的结构成员,该成员是使用 lambda 函数的结构向量
- 在结构向量中搜索一个数据成员,然后打印匹配的所有数据成员