繁体   English   中英

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

[英]Declaring a vector of pointers to vector of strings

我有一个二维字符串表(使用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);

[更正]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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