擦除(remove_if())异常 [英] erase(remove_if()) anomaly
问题描述
我创建了一个函数来运行一个字符串的向量,并删除任何长度3或更小的字符串。这是使用STL算法库的一个教训。
I've created a function to run through a vector of strings and remove any strings of length 3 or less. This is a lesson in using the STL Algorithm library.
我遇到麻烦,功能工作,但不仅删除长度3或更小的字符串,但它也将字符串vector附加到结尾。
I'm having trouble in that the functions work but not only does it delete strings of length 3 or less but it also appends the string "vector" to the end.
输出应为
This test vector
,而是
This test vector vector"
如何解决?
/*
* using remove_if and custom call back function, write RemoveShortWords
* that accepts a vector<string> and removes all strings of length 3 or
* less from it. *shoot for 2 lines of code in functions.
*/
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;
bool StringLengthTest(string test) //test condition for remove_if algo.
{
return test.length() <= 3;
}
void RemoveShortWords(vector<string> &myVector)
{
//erase anything in vector with length <= 3
myVector.erase(remove_if(myVector.begin(),
myVector.end(),
StringLengthTest));
}
int main ()
{
//add some strings to vector
vector<string> myVector;
myVector.push_back("This");
myVector.push_back("is");
myVector.push_back("a");
myVector.push_back("test");
myVector.push_back("vector");
//print out contents of myVector (debugging)
copy(myVector.begin(), myVector.end(), ostream_iterator<string>(cout," "));
cout << endl; //flush the stream
RemoveShortWords(myVector); //remove words with length <= 3
//print out myVector (debugging)
copy(myVector.begin(), myVector.end(), ostream_iterator<string>(cout," "));
cout << endl;
system("pause");
return 0;
}
推荐答案
如果你分离语句:
auto iter(remove_if(myVector.begin(), myVector.end(), StringLengthTest));
myVector.erase(iter);
这两行与您的单行相同。而且现在应该清楚错误是什么。 remove_if,先工作。它遍历整个向量,并将所有选定条目移动到结束(更好地说:它将未选择的条目移动到前面)。在它运行后,它返回一个迭代器到左边的条目的最后位置,如:
These 2 lines do the same as your single line. And it should be clear now what the "bug" is. remove_if, works first. It iterates over the whole vector and moves all "selected" entries "to the end" (better said: it moves the non selected entries to the front). After it has run it returns an iterator to the "last" position of the left over entries, something like:
this
test
矢量
test< - 迭代器指向此处
矢量
this
test
vector
test <- iterator points here
vector
然后你用一个迭代器运行擦除。这意味着你擦除一个指向的元素 - 所以你擦除测试元素。
Then you run erase with a single iterator. That means you erase a single element pointed at - so you erase the "test" element. - What is left over is what you are seeing.
要修复它,只需从remove_if返回的向量中删除end():
To fix it simply erase from the vector returned by remove_if to the end().:
myVector.erase(remove_if(myVector.begin(), myVector.end(), StringLengthTest), myVector.end()); //erase anything in vector with length <= 3
这篇关于擦除(remove_if())异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!