gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:45:40 26 4
gpt4 key购买 nike

我想创建一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com