我有一个包含STL向量的对象.我从矢量大小为零开始,并使用push_back它来添加它.所以,push_back工作正常.
在我的代码中,向量中的每个元素代表一个原子.因此,该STL载体在其内部的对象是"分子".
当我试图从我的分子中移除一个原子,即从阵列中擦除其中一个元素时,该erase()功能不起作用.其他方法可以工作,如size()和clear().clear()删除所有元素,这是过度的.erase()正是我想要的,但由于某种原因它不起作用.
这是我的代码的一个非常简化的版本.但是,它确实代表了问题.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class atomInfo
{
/* real code has more variables and methods */
public:
atomInfo () {} ;
};
class molInfo
{
/* There is more than 1 atom per molecule */
/* real code has more variables and methods */
public:
vector <atomInfo> atom;
molInfo () {};
};
int main ()
{
int i;
molInfo mol;
for( i=0; i<3 ; i++)
mol.atom.push_back( atomInfo() );
//mol.atom.clear() ; //Works fine
mol.atom.erase(1) ; //does not work
}
Run Code Online (Sandbox Code Playgroud)
我使用时收到以下错误erase():
main.cpp:在函数'int main()'中:main.cpp:39:21:错误:没有匹配函数来调用'std :: vector :: erase(int)'mol.atom.erase(1);
看起来你认为std::vector::erase从容器的开头拿了一个索引.
目前还不清楚你从哪里得到这个想法,因为它不是文档所说的.
这些函数与迭代器一起使用.
幸运的是,使用向量,您可以通过向迭代器添加数字来获得所需的效果.
像这样:
mol.atom.erase(mol.atom.begin() + 1);
Run Code Online (Sandbox Code Playgroud)
事实上,所述文件确实有一个这样的例子.