gpt4 book ai didi

C# Arraylist 的 C++ 等价物,用于保存多种数据类型

转载 作者:搜寻专家 更新时间:2023-10-31 01:54:50 24 4
gpt4 key购买 nike

寻找与 C# 的 Arraylist 集合类匹配的等效容器类。有没有什么东西可以提供基于索引的枚举以及容纳多种数据类型的容器。

我想做的是实现一个模型- View - Controller 。我正在尝试创建一个 Controller ,它可以在内部管理不同类型的形状数据类型(例如:Box2D、Circle2D、Circle3D 等)

//Controller code
class Controller
{
//internally track all shapes...

void CreateShape(const Box2d &box);
void CreateShape(const Box3d &box);
void CreateShape(const Circle2d &circle);

//More Add/Edit/Remove Shape methods...

void Reset(); //clear the container of shapes...
};

我正在尝试创建一个 vector 或不同类型的容器来容纳多种数据类型。例如:

//Is this line of code possible??
vector <int, string> vec;

int i=0;
string str = "test";

//add different data-type objs into my vector mutable array
vec.push_back(i);
vec.push_back(str);

请告知,如果 C++ 中还有其他容器类可以帮助我实现此功能,或者有一种方法可以使用 vector 类来存储多种数据类型。

最佳答案

你可能想要这样的东西:

class Shape {
public:
virtual void rotate(double degrees) = 0;
virtual void scale(double newScale) = 0;
virtual ~Shape(){}
//etc, etc, etc...
};

class Box2d : public Shape {
public:
virtual void rotate(double degrees) {
//Code for rotating...
}

//Implement other virtual methods...
};
class Circle2d : public Shape {}; //Implement virtual methods
class Box3d : public Shape {}; //Implement virtual methods


int main() {
vector<Shape*> items;
items.push_back(new Box2d());
items.push_back(new Circle2d());

//Now doing this:
items[i]->rotate(180.0);
//Will call Box2d's rotate function
}

关于C# Arraylist 的 C++ 等价物,用于保存多种数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9164894/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com