C++如何实现列表的数组

C++ how to implement an array of list

本文关键字:列表 数组 实现 何实现 C++      更新时间:2023-10-16

我正在将一部分代码从C#翻译成C++。

我的观点是:

Class Point
{
public int X;
public int Y;
}
const int MAX = 256;
public void ComputePoints(Byte[] image,
int width, 
int height,
out List<Point>[] listPixels)
{
listPixels = new List<Point>[MAX];
//etc..
}

(我简化了这段代码,只显示了有趣的部分)。

我的问题涉及out List<Point>[] listPixels。我试着用翻译这个

public void ComputePoints(unsigned char[] image,
int width, 
int height,
std::vector<Point> *listPixels[])
{
*listPixels = new std::vector<Point>[MAX];
//etc..
}

但是我有错误

分段错误。

如何在C++中编写out List<Point>[] listPixels的最简单等价物?

由于List<Point>[]是一个列表数组,您可以使用嵌套向量(向量的向量)来获得所需的行为:

std::vector<std::vector<Point> >

请注意,在两个>之间添加一个空格可能很重要。有些编译器没有它就无法编译。

现在,您可以像一样将矢量作为参考进行传递

void ComputePoints(... , std::vector<std::vector<Point> > &listPixels)
{
...

为什么不按值返回矢量的矢量?在C++11和更新版本中,它速度快,代码更容易理解。

struct Point {
int x;
int y;
};
const int MAX = 256;
std::vector<std::vector<Point>> computePoints(const unsigned char image[], int width, int height) {
std::vector<std::vector<Point>> points(MAX);
// Here goes the code that does the calculations and fills 'points'.
return points;
}

对于固定大小的数组,可以使用std::array。

您不需要在c++中使用new,只需使用堆栈即可,这是从c#/java转换到c++时常见的问题。

对于简单的对象,您几乎不需要动态分配它们(使用new),如果必须动态分配它们,请不要将原始拥有指针与new一起使用,而是使用智能指针(std::unique_ptr,std::shared_ptr)。这不仅是在c++中创建对象的方式,在堆栈上分配对象也比堆更快,而且您有更好的局部性。

#include <list>
#incldue <array>
const int MAX = 256;
std::array<std::list<Point>, MAX> array_list;

我也喜欢键入def这样的长类型:

using MyContainer = std::array<std::list<Point>, 256>;
MyContainer array_list;
would be one way to have a array of lists

如果你不一定需要列表,你也可以使用std::vector(它应该是你的默认容器),它提供了更多的位置

对于C++11之前的版本(正如您在其他答案中所发现的),您也可以使用std::vector而不是std::array,这将分配堆上的项,但这应该是可以的,因为与普通C数组相比,std::vector提供了更好的功能。

或者,如果您真的想使用C数组:简单堆叠:

std::list<Point> my_list_array[MAX];

和堆分配的版本:

std::list<Point>* my_list_array = new std::list<Point>[MAX];
//but don't forget about the delete[]!