std::remove 不起作用
问题描述:
我的测试程序的目标是擦除一个简单的字符串向量中的单元格,如下所示.程序失败(分段错误).
The goal of my test program is to erase a cell in a simple vector of strings like below. The program fail (segmentation fault).
static void display(std::vector<std::string> const &vec)
{
std::vector<std::string>::const_iterator It = vec.begin();
for (; It != vec.end(); ++It)
std::cout << *It << " ";
std::cout << std::endl;
}
int main(void)
{
std::vector<std::string> vec;
size_t index = 0;
vec.push_back("Toto");
vec.push_back("Titi");
vec.push_back("Tata");
vec.push_back("Tutu");
display(vec);
std::vector<std::string>::iterator It = vec.begin();
for (size_t idx = 0; It != vec.end(); ++It, idx++)
if (!(*It).compare("Tutu"))
index = idx;
vec.erase(std::remove(vec.begin(), vec.end(), index), vec.end()); //Segmentation fault
display(vec);
getchar();
return (0);
}
有人可以帮我吗?预先感谢您的帮助.
Does anyone can help me? Thanks in advance for your help.
答
vec.erase(std::remove(vec.begin(), vec.end(), index), vec.end());
您需要将实际元素(在本例中为 std::string
类型)传递给您的 erase
函数.
You need to pass the actual element (in this case of type std::string
) to your erase
function.
所以应该是 somestring