C++ 创建链接向量和列表

C++ 创建链接向量和列表,c++,list,vector,stl,C++,List,Vector,Stl,我想创建一个向量,它存储指向列表的指针,如图所示。 我不知道这里需要多少清单。所以,我想写这样的函数 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

我想创建一个向量,它存储指向列表的指针,如图所示。 我不知道这里需要多少清单。所以,我想写这样的函数

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.

}
矢量地址//节点是类。

如果((int)address.size()要使用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;

}
此外,如果由于
>
而出现错误,请将其编译为C++11,或将
地址编写为:

 std::vector<std::list<std::string>> address;
 std::vector<std::list<std::string> > address;
std::向量地址;

不太清楚,但我想您需要一个自动调整大小的容器(作为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);
    }
};
其他建议:

  • 如果您计划在其中放入大量项,并且不需要在连续地址中包含所有列表对象(即向量与C数组的兼容性),我建议您使用
    deque
    而不是
    vector
    ,或者使用
    reserve
    提供适当大小的提示,否则您可能会感到奇怪,为什么有时在不存在的列表中添加单个字符串会如此缓慢
  • STL到处都使用基于0的索引。定义基于1的索引只会让您感到困惑,所以从0开始计算列表(在上面的示例中,只需将
    索引-1
    替换为
    索引
    ),然后计算应用程序逻辑)

大概因为Nikhil正在向链表添加字符串,所以实际上是
std::vector collection
;收集(编号)。推回(名称)有效吗?[用于在corresp.list中插入名称]@Nikhil,如果您在我的注释中声明您的类型,则会这样做。对于while循环,我将写入:A.push(std::list temp)//这将在向量中添加空列表,对吗?[将temp声明为字符串类型的列表]@Nikhil是的,它将向向量添加emtpy列表。你可以在矢量上使用<代码>()(代码)>方法来获取最后一个元素。只使用C++(2011)标准库:<代码> STD::向量地址;<代码>这称为锯齿阵列,顺便说一句。
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"