C++如何实现列表的数组
C++ how to implement an array of list
我正在将一部分代码从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[]!
- C++如何生成std::数组列表
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- C++未知长度字符串的数组,其行为类似于 Python 字符串列表
- GTEST : 如何将数组列表作为参数传递到 ValuesIn of INSTANTIATE_TEST_CASE_P?
- 基于数组的列表 - 动态数组创建时出错
- 如何使用列表/数组在C++中实现 Python "... not in ..."?
- 从非托管 C# DLL 返回列表/数组
- C++对象列表数组
- 如何在C++中创建配对列表数组
- 链接列表数组
- 获取列表数组中的所有列表项
- 如何创建和扫描列表/数组..在嵌入式剪辑中
- 列表数组<string>,插入字符串行为奇怪
- 对 STL 列表数组使用迭代器的语法
- 在类|C++中创建分数列表数组
- C++是否有一些类似C#类型的东西来存储列表/数组中的类类型
- 列表数组-构造函数和main()中的地址不匹配
- c++中的列表数组.指针;/
- STL 列表数组无法访问列表函数
- 用动态内存管理创建类列表数组