4

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

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 库。

4

2 回答 2

4

如果你想使用 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;
于 2013-09-15T09:39:26.180 回答
1

这不是很清楚,但我想你想要一个自动调整大小的容器(作为 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);
    }
};

您可能希望从此类容器中获得的任何其他内容可能已经在vectorlist模板类中实现(查看 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"

其他建议:

  • 如果您打算在其中放置很多项目并且不需要将所有列表对象放在连续地址(即向量与 C 数组的兼容性),我建议您使用 adeque而不是 a vector,或者提供适当的大小提示reserve,否则您可能会想知道为什么有时在一个尚不存在的列表中添加单个字符串会如此缓慢。
  • STL 到处使用从 0 开始的索引。您只会因定义一个基于 1 的列表而感到困惑,因此从 0 开始计算您的列表(只需在上面的示例中替换index - 1index)并对应用程序逻辑进行数学计算)
于 2013-09-15T10:10:22.007 回答