我正在制作各种各样的层次结构,并且无法在向量中添加元素。我简化了代码,仍然无法按预期向向量添加元素。层次结构如下:
Pdb>链>字符串
Pdb和Chain是类名,字符串是属于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函数本身添加一个元素,但是当我将GetStrings返回main时,执行AddString后,字符串为空。我不明白为什么会这样。任何帮助将不胜感激。
答案 0 :(得分:4)
问题是您返回该成员的副本,而不是成员本身:
vector<Chain> GetChains()
应该是
vector<Chain>& GetChains()
为此工作。
我必须指出,你严重违反了单一责任原则。你直接对会员进行操作,这不是一个好主意。考虑更换:
pdbs[0].GetChains()[0].AddString("Whateva");
类似
pdbs[0].AddStringToChain(0,"Whateva");