我有一个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];
}我觉得这可能是一个非常简单的切换,但我没有太多使用向量的经验,我不确定从哪里开始。任何指导都是非常感谢的!
发布于 2011-10-12 11:31:25
看起来您正在尝试创建某种形式的多维向量。您是否考虑过使用boost?http://www.boost.org/doc/libs/1_47_0/libs/multi_array/doc/user.html
发布于 2011-10-12 11:38:27
要做到这一点,最简单的方法就是使用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);已更正
https://stackoverflow.com/questions/7734944
复制相似问题