c++ - 创建链接 vector 和列表

标签 c++ list vector stl

我想创建一个 vector ,它存储指向列表的指针,如图所示。 This is how it looks 我不知道这里需要多少列表。所以,我想写这样的函数

vector<node*> address; //node is class.
if ((int)address.size()<number)  //number is integer taken as input to function.
    { while((int)address.size()!=number)
        {address.push(/*here I want some function which will generate
 empty list and return pointer to head node or any information 
that will help to access list later*/)
        }
else
{    address[number-1].push_back(name); //name has type string;
//this line may be wrong for syntax but idea is A[i] gives me 
   // list where I want to put name.

}

最好使用STL库。

最佳答案

如果你想使用STL库,那就用

std::vector<std::list<node>> address; //node is class (note that you can pass size here)

// Using your code in your code:
if ((int)address.size() < number)  //number is integer taken as input to function.
{
        address.resize(number);
}
else
{    address.back().push_back(name); //name has type string;

}

请注意,节点 是您要插入 vector 的元素的类型。正如@john 所说,如果您想保留一个字符串列表,请将 address 声明为:

 std::vector<std::list<std::string>> address;

另外,如果你因为 >>> 而出错,要么将其编译为 C++11,要么将 address 写为:

 std::vector<std::list<std::string> > address;

关于c++ - 创建链接 vector 和列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18810910/

相关文章:

c++:将模板声明为类成员

c++ - C++ 中的退出功能不起作用

python - 创建列表列表

Java 或 Kotlin - 创建尽可能多的子列表

c++: 将 vector<char> 转换为 double

ruby - 面向对象的 Ruby 中的向量加法

c++ - 如何在 C++ 中返回唯一所有权

.net - 从自定义类型 F# 的列表中过滤不同的值

c++ - 为什么要在实例替换 vector 中删除?

c++ - Boost.Spirit.Qi : dynamically create "difference" parser at parse time