声明一个指向字符串向量的指针向量

Declaring a vector of pointers to vector of strings

本文关键字:向量 字符串 指针 一个 声明      更新时间:2023-10-16

我有一个2D的字符串表(使用STL向量),我试图修改,使表是指向字符串向量的指针向量。我知道这将需要更改构造函数,以便动态创建行,并将指向行的指针插入表中,但我不确定如何首先创建这个表。

在我的。h文件中:
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;
};

在我的。cpp文件中:

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];
}

我觉得这可能是一个相当容易的转换,但我没有很多使用向量的经验,我不知道从哪里开始。任何指导是非常感激的!

看起来您正在尝试创建某种形式的多维向量。你考虑过使用boost吗?http://www.boost.org/doc/libs/1_47_0/libs/multi_array/doc/user.html

最简单的方法是使用typedef。此外,你似乎在你的头文件中使用'using'子句-你永远不应该这样做。

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

不要忘记,当添加一个现在,你将需要分配内存:

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);
(纠正)