简体   繁体   中英

Declaring a vector of pointers to vector of strings

I have a 2D table of strings (using STL vector) and am trying to modify so that the table is a vector of pointers to vectors of strings. I know that this will require changing the constructor so that rows are created dynamically, and pointers to the rows are inserted into the table, but I'm not sure how to go about creating this table in the first place.

In my .h file:

class StringTable
{
public:

    StringTable(ifstream & infile);

    // 'rows' returns the number of rows
    int rows() const;

    // operator [] returns row at index 'i';
    const vector<string> & operator[](int i) const;

private:
    vector<vector<string> >  table;

};

In my .cpp file:

StringTable::StringTable(ifstream & infile)
{
    string          s;
    vector<string>  row;

    while (readMultiWord(s, infile))  // not end of file
    {
        row.clear();
        do
        {
            row.push_back(s);
        }
        while (readMultiWord(s, infile));
        table.push_back(row);
    }
}

int StringTable::rows() const
{
    return table.size();
}

const vector<string> & StringTable::operator[](int i) const
{
    return table[i];
}

I feel like this is probably a pretty easy switch, but I don't have a lot of experience using vectors, and I'm not sure where to start. Any guidance is greatly appreciated!

It looks like you are trying to create some form of multidimensional vector. Have you considered using boost? http://www.boost.org/doc/libs/1_47_0/libs/multi_array/doc/user.html

OK the easiest way to do this is with typedef. Also it seems that you are using 'using' clauses in you header files - you should never ever do this.

class StringTable
{
    public:
         typedef std::vector<std::string> Strings_t;
         std::vector<Strings_t *> table;
};

Dont forget when adding a now you will need to allocate memory ie:

StringTable tbl;
StringTable::Strings_t *data_ptr=new StringTable::Strings_t;

data_ptr->push_back("foo");
data_ptr->push_back("bar");

tbl.table.push_back(data_ptr);

[Corrected]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM