我创建了一个函数来遍历字符串向量并删除长度为 3 或更短的任何字符串。这是使用 STL 算法库的一课。
我在函数工作时遇到了麻烦,但它不仅会删除长度为 3 或更短的字符串,而且还会将字符串“vector”附加到末尾。
输出应该是
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;
}