Search code examples
c++vectoriostdvectorstdlist

Outputting a vector of of lists in C++


I'm having trouble outputting my vector of lists:

class index_table {

public:
    index_table() { table.resize(128);}
    void insert(string &, int );

private:
    class entry
    {
        public:
        string word;
        vector <int> line;
    };

    vector< list <entry> > table;
};

I've got it so that it will fill up:

int main ()
{
index_table table;
string word,
int num = 5; //this is going to a random number. 5 is a temp. place holder.

while (cin >> word)
    table.insert(word, num);

}

but how to output it? I've tried many different approaches, but a lot of them are giving me errors.
Do I have to overload the operator? I'm not entirely sure how I will be able to do it.


Solution

  • Assuming you really have a good reason to use std::vector< std::list<entry> >, then based on the given structure, printing of words might look like this:

    class index_table {
    public:
        void print() {
            for (size_t i = 0; i < table.size(); ++i) {
                std::list<entry>::iterator li;
                for (li = table[i].begin(); li != table[i].end(); ++li)
                    std::cout << li->word << " ";
            }
        }
        ...
    
    private:
        std::vector< std::list<entry> > table;
        ...
    };