如何初始化对象列表的向量.我知道很困惑

How do I Initialize a vector of lists of objects. Confusing I know

本文关键字:我知道 向量 初始化 对象 列表      更新时间:2023-10-16

我正在创建一种非常粗糙的hashtable。它将读取一个 ASCII 文本文件,并将所有单词与找到的单词的行号一起存储到链表中。它使用单词第一个字母的数值来查找列表以存储单词,然后在列表中搜索单词的任何条目,如果未找到,则向列表中添加一个新条目,否则它将行号添加到匹配的条目中。

我只是不知道如何初始化vector.它需要 128 个列表(每个 ASCII 值一个(。

另请注意,我无法使用std::map

我知道使用整数向量,您可以vector<int> vector_name(128,0)获得 128 个值为 0 的条目。我基本上想这样做,但有 128 个空的entry列表。

这是我到目前为止的代码

#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
class index_table {
    public:
        void insert(string key, int value);
        vector<int>& find(string key);
    private:
        class entry{
            public:
                string word;
                list<int> line_numbers;
        };
        vector<list<entry> > table;
};
int main(){
    return 0;
}

在你还没有的构造函数中你可以做: table.resize(128);现在table是一个由 128 个空std::list entry对象的向量。

class index_table {
public:
    void insert(string key, int value);
    vector<int>& find(string key);
    //My ctor
    index_table(size_t len) : table(len), len(len) 
    {
        //some other stuff someday
    }
private:
    //not sure why you want to make entry private but ok...
    class entry{
        public:
            string word;
            list<int> line_numbers;
    };
    //some typename convenience for your iterators
    typedef entrylist list<entry>;
    typedef entrytable vector<entrylist>;
    entrytable table;
};