我正在制作各种层次结构,并且无法将元素添加到向量中。我简化了代码,但仍然无法按预期向向量添加元素。层次结构如下所示:
Pdb > 链 > 字符串
Pdb 和 Chain 是类名,strings 是属于 Chain 的向量的名称。我无法 push_back 将字符串添加到字符串。查看我的代码,您可能会更好地了解:
链类:
class Chain {
string chain_id;
vector<string> strings;
public:
Chain(string id_) { chain_id = id_; }
vector<string> GetStrings() { return strings; }
void AddString(string s) {
cout << "Size of strings BEFORE push_back in AddString: " << strings.size() << endl;
strings.push_back(s);
cout << "Size of strings AFTER push_back in AddString: " << strings.size() << endl;
}
string GetChainId() { return chain_id; }
};
pdb类:
class Pdb {
string pdb_id;
vector<Chain> chains;
public:
Pdb(string id_) { pdb_id = id_; }
vector<Chain> GetChains() { return chains; }
void AddChain(Chain c) { chains.push_back(c); }
string GetPdbId() { return pdb_id; }
};
主要的:
int main () {
vector<Pdb> pdbs;
pdbs.push_back(Pdb("1ubq"));
cout << "\n\t1. " << pdbs[0].GetPdbId() << endl;
pdbs[0].AddChain(Chain("A"));
cout << "\n\t2. " << pdbs[0].GetChains()[0].GetChainId() << endl;
pdbs[0].GetChains()[0].AddString("Whateva");
cout << "\n\t3. Size of strings after AddString in main: " << pdbs[0].GetChains()[0].GetStrings().size() << endl;
return 0;
}
这输出:
1. 1ubq
2. A
Size of strings BEFORE push_back in AddString: 0
Size of strings AFTER push_back in AddString: 1
3. Size of strings after AddString in main: 0
正如您所看到的,AddString 函数正在向 AddString 函数本身内的 stings 添加一个元素,但是当我在 main 中返回 GetStrings 时,在执行 AddString 之后,字符串为空。我不明白为什么会这样。任何帮助将非常感激。