gpt4 book ai didi

c++ - 执行 remove_if() 后删除()

转载 作者:IT老高 更新时间:2023-10-28 21:35:54 24 4
gpt4 key购买 nike

我创建了一个函数来遍历字符串 vector 并删除长度为 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;
}

最佳答案

如果将语句分开,最容易理解这一点:

auto iter(remove_if(myVector.begin(), myVector.end(), StringLengthTest));
myVector.erase(iter);

这两行与您的单行相同。现在应该清楚“错误”是什么。 remove_if,首先工作。它遍历整个 vector 并将所有“选定”条目移动到“末尾”(更好地说:它将未选定的条目移动到前面)。运行后,它会将迭代器返回到剩余条目的“最后”位置,例如:

this
test
vector
test <- iterator points here
vector

然后您使用单个迭代器运行删除。这意味着您删除了指向的单个元素 - 因此您删除了“测试”元素。 - 剩下的就是你所看到的。

要修复它,只需从 remove_if 返回的 vector 中删除到 end()。:

myVector.erase(remove_if(myVector.begin(), myVector.end(), StringLengthTest), myVector.end()); //erase anything in vector with length <= 3

关于c++ - 执行 remove_if() 后删除(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9053883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com