[英]Create a linked vector and lists
我想创建一个存储指向列表指针的向量,如图所示。 我不知道这里需要多少个列表。 所以,我想写这样的函数
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;
}
请注意, node
是要推入向量的元素的类型。 正如@john所说,如果你想保留一个字符串列表,那么将address
声明为:
std::vector<std::list<std::string>> address;
此外,如果由于>>
出现错误,请将其编译为C ++ 11,或将address
写为:
std::vector<std::list<std::string> > address;
它不是很清楚,但我想你想要一个自动调整大小的容器(作为javascript向量),其中列表索引是基于1的(即地址0没有列表)和一个在给定索引的一个列表的末尾插入的方法。 基本上是这样的:
struct MyCollection: public std::vector<std::list<std::string> > {
void push_at(size_t index, const std::string& item) {
resize(std::max(size(),index - 1);
at(index - 1).push_back(item);
}
};
您可能希望从这样的容器中获得的任何其他内容可能已经在vector
和list
模板类中实现(请查看stl文档以查看可用的内容),例如:
MyCollection a; //declares an empty collection
a.push_at(6,"hello"); //create 6 lists and inserts "hello" at the end of the last one
a[5]; //gets 6th list (method [] is 0-based on vector)
a.push_at(6,"hi"); // since list already exists it just adds "hi" at the end
a[5].front() //"hello"
a[5].back() //"hi"
其他建议:
deque
而不是vector
,或者提供适当的大小提示有reserve
,否则你可能会发现自己想知道为什么有时在列表中添加一个不存在的字符串是如此之慢。 index
替换index - 1
)并对应用程序逻辑进行数学计算)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.