我想创建一个 vector ,它存储指向列表的指针,如图所示。 我不知道这里需要多少列表。所以,我想写这样的函数
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/