std :: list c的数组 [英] array of std::list c
问题描述
我找不到对此的任何人工解释: 我如何创建像这样的列表数组
I can't find any human explaination for this: how can I create an array of lists like
std::list<int> mylist[size] ?
如果我将其放在程序中,它会编译但会产生一些问题,因为它不执行任何代码(如果我写出不带[size]的mylist,其余代码也可以正常工作)
If I put this in my program it compiles but creates some problems since it doesn't execute any code (the rest of the code works just fine if I write mylist w/out [size])
我在某处读到,不建议使用C的原始数组. 有哪些替代方案?
I was reading somewhere that using primitive arrays of C is not recommended; what are the alternatives?
对不起,谢谢
推荐答案
您的声明不正确,并且在C ++中不受支持.您试图在运行时声明一个可变大小的数组,这是C99的功能,但不是C ++中的功能.参见此处:运行时的数组大小无动态可以分配吗?
Your declaration is incorrect, and not supported in C++. You're trying to declare a variable-sized array at run-time, which IS a C99 feature, but is not in C++. See here: Array size at run time without dynamic allocation is allowed?
您有这个:
std::list<int> mylist[size]
这是您需要的:
std::list<int> mylist[] = new std::list<int>[size];
但这仍然不是一个好主意,因为您稍后需要使用delete []
对其进行取消分配.正如其他人所说的,您可以通过几种不同的方式来做到这一点,所有这些方式对于c ++都是更好的:
But this is still a bad idea, as you need to de-allocate it later with delete []
. As others have said, you can do it a couple of different ways, all of which are better for c++:
std::list< std::list< int > > myListOfLists; // Linked list of linked lists
std::vector< std::list< int > > myVectorOfLists; // Better, a vector is more like an array
std::array<std::list<int>, 10> this_would_do; // From above, only works if you know the array size at compile-time
希望这对您有所帮助.
这篇关于std :: list c的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!