簡體   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