Windows Visual Studio C++列表列表



Windows list 发现以下帖子有些帮助,但我仍在挣扎。

在 c++ 中创建列表列表

我需要的是字符串列表的列表。

所以:

#include <list>
typedef list<std::string, allocator<std::string>>> LISTSTR;
typedef list<LISTSTR, allocator<LISTSTR>> LISTLISTSTR;  // uncertain what this is doing?!!?
main()
{
LISTLISTSTR records;
// Add a blank string list to the list
LISTSTR *rowoffields = new LISTSTR();
rowoffields->insert(string("Field1"); // also tried new string("Field1")
records.insert(rowoffields);  // also tried *rowoffields
}

但这返回编译错误:

no instance of overloaded function "std::list<_Ty,_Alloc>::insert[with _Ty=std::string, _Alloc=std::allocator<std:string>]" matches the argument list
argument types are (std::string)  // or types are (std::string*) if using new string("Test")
object type is: LISTSTR
no instance of overloaded function "std::list<_Ty,_Alloc>::insert[with _Ty=LISTSTR, _Alloc=std::allocator<LISTSTR>]" matches the argument list
argument types are (LISTSTR*)  // or types are (LISTSTR) if using *rowoffields
object type is: LISTLISTSTR

这里有一种方法可以做到这一点,它可能更接近Python的正常用法。我们首先声明一个指向字符串列表的指针数组(预先指定类型,而不是 Python-duck-typed(尽管我们可以使用模板来做到这一点(。然后,我们以内存安全的方式(无泄漏(使用这些指针来创建新列表。请注意,在此特定设置中,列表总数在编译时是固定的(并且等于 const int SIZE(,指针数组位于堆栈上,但指针指向的列表都是在堆上动态分配的。(您可以使用new和delete来执行此操作,但是较新的智能指针确实是要走的路(。

#include <list>         
#include <memory>       //for the smart pointers
#include <iostream>    
const int SIZE = 3;
int main() {
//make an array of smart pointers to list of strings:
std::unique_ptr<std::list<std::string>> myLists[SIZE];
//use each smart pointer in the list to make a new list:
for (int i = 0; i < SIZE; i++) {
myLists[i] = std::make_unique<std::list<std::string>>();
}
//load each new list with a single string:
myLists[0]->push_front("Hello");
myLists[1]->push_front("World,");
myLists[2]->push_front("I'm C++!");
//print the results
for (int i = 0; i < SIZE; i++) {
std::cout << myLists[i]->front() << " ";
}
std::cout << std::endl;
return 0;
}

现在,如果您希望能够在运行时向列表列表添加更多列表,则必须动态分配指向列表的指针数组,而不是像此示例中那样使用静态(自动(分配。 (编辑:或者,您可以设置一些上限,例如 100,然后将其设置为应用程序中列表的最大数量。可能想使用 std::array 来保存该指针列表,而不是上面的普通数组,因为 std::array 像 Python 一样进行边界检查(。 对于更简单的版本:

#include <list>
//remove typedefs
int main() {      //notice the int!
const int SIZE = 10;
//make array of pointers to list of strings (on stack, fixed size)
std::list<std::string>* myLists[SIZE];
//use pointer to make new list on heap:
myLists[0] = new std::list<std::string>;
//use pointer syntax (instead of . use ->) to call list functions
myLists[0]->push_front("Old style C++");
//more code...
//when finished must remember to free that memory:
delete myLists[0];
//and not leave a dangling pointer:
myLists[0] = nullptr;
return 0;
}

最新更新