将2d数组转换为2d对象向量
Converting a 2d array to 2d vector of objects
我有以下代码,我试图将二维数组转换为二维向量。
int main()
{
const string ID_BASE = "56-123-";
const int NUM_AISLES = 2;
const int NUM_SHELVES = 3;
// Declare 2-D array of objects.
//Product products[NUM_AISLES][NUM_SHELVES];
Product **products;
int idNum = 0;
int i, j;
products = new Product *[NUM_AISLES];
// Add a set of candy bars (all same price).
for (i = 0; i < NUM_AISLES; i++)
{
products[i] = new Product[NUM_SHELVES];
for (j = 0; j < NUM_SHELVES; j++)
{
// Build up id number using string stream.
stringstream id;
id << ID_BASE << setfill('0') << setw(2) << idNum;
products[i][j].set(id.str(), 0.50, true);
idNum++;
}
}
// Increase prices and output each product.
for (i = 0; i < NUM_AISLES; i++)
{
// Increase price for all products in aisle
// (recall products is 2-d, but function
// increasePrice() wants 1-d array).
increasePrice(products[i], NUM_SHELVES, 1.0);
for (j = 0; j < NUM_SHELVES; j++)
{
// Output individual product in 2-d array.
products[i][j].output();
cout << endl << endl;
}
}
几乎我所有关于多维向量的搜索都是基于基本数据类型的,而我试图创建对象的二维向量这一事实让我很困惑。有人能给我解释一下吗?
我只是给你一个简单的例子来初始化对象的2D矢量,希望这将帮助你开始:
#include <vector>
class Foo {};
typedef std::vector<Foo> FooVector;
typedef std::vector<FooVector> FooMatrix;
main(){
FooMatrix X;
for (int i=0;i<imax;i++){
FooVector Y;
for (int j=0;j<jmax;j++){
Y.push_back(Foo());
}
X.push_back(Y);
}
// ... this is equivalent to ...
FooMatrix X2 = FooMatrix(imax,FooVector(jmax,Foo()));
}
和if有一个接受vector的函数:
void bar(FooVector x,int y){ /*...*/ }
你可以这样调用它:
for (int i=0;i<X2.size();i++){
bar(X2[i],i);
// ... or ...
bar(X2.at(i),i);
}
使用二维向量:
1)你可以使用vector<vector<Product *>>
产品;
vector<vector<Product *> > products;
products[i].push_back(new Product());
记住,一旦通过指针完成,就释放对象。
2)可以使用vector<vector<Product>>
产品;
products[i].push_back(Product());
如果你决定用指针存储它们,你必须管理这些对象的分配/释放。
还有很多其他的事情要注意:指针向量
另一方面,在vector中通过副本存储对象将提供更好的引用位置。
相关文章:
- 在C++中将对象添加到 2D 矢量
- 使用 c++ 将 2d CAD 对象转换为 TIFF 格式
- 我有一个 Qt 对象的 2d 数组,我已经用值播种了这些对象。如何访问数组中特定对象的值并更改它们?
- 类对象指针C 的2D向量
- 如何在C 2D向量中找到对象(而不是int)的位置
- 将每个对象渲染到空间中,并在3D场景上渲染2D场景
- 如何在C 中打印一个对象的2D向量
- 无法用2D矢量成员引用对象
- 如何使用结构在 2d 数组中移动玩家对象
- 无法使用 opengl 正确旋转 2D 对象
- C 2D对象的动态数组
- 在OpenGL中将2D对象移动到一个点
- 存储2D对象阵列的最佳方法是什么
- C++ 类变量不会保留从另一个类传递的 2d 对象数组中的值
- 想要移动一个2d对象而不是另一个
- 将2d数组转换为2d对象向量
- 用2个着色器渲染两个重叠的2D对象
- 不能访问2d对象指针数组的类成员(类型***)
- 2D对象阵列内存问题C++
- 如何在不移动整个场景的情况下移动一个2d对象?