对于学校作业,我需要通过使用来消除矢量中的紫色,这就是我想出的:
bool IsEqual(string s, string s2)
{
if (s == s2)
{
return true;
}
}
int main() {
vector<string> coulours2 = { "red", "green", "blue", "orange", "purple", "orange", "black", "green" };
vector<string>::iterator newEnd;
newEnd = remove_if(coulours2.begin(), coulours2.end(), bind2nd(IsEqual, "purple"));
colours2.erase(newEnd);
cin.get();
return 0;
}
但是我遇到了很多错误,我认为我使用的是bind2nd错误。我应该如何正确使用它?
答案 0 :(得分:5)
对于初学者,不推荐使用std::bind1st
和std::bind2nd
函数。您应该考虑使用std::bind
,这样更通用,更易于使用。
如果您 想要使用bind2nd
,那么您传入的函数必须是自适应函数,这是一种导出一些额外类型的函数对象类型信息。要将原始函数指针转换为自适应函数,请使用有趣的ptr_fun
函数:
remove_if(coulours2.begin(), coulours2.end(),
bind2nd(ptr_fun(IsEqual), "purple"));
但是,根本不需要在这里定义自己的功能。只需使用std::equal_to
:
remove_if(coulours2.begin(), coulours2.end(),
bind2nd(equal_to<string>(), "purple"));
正如评论中提到的,您还使用erase/remove_if
模式不正确。试试这个:
coulours2.erase(remove_if(coulours2.begin(), coulours2.end(),
bind2nd(equal_to<string>(), "purple")),
coulours2.end());
使用std::bind
执行此操作的“更好”方式如下所示:
using namespace std::placeholders;
coulours2.erase(remove_if(coulours2.begin(), coulours2.end(),
bind(equal_to<string>(), _1, "purple")),
coulours2.end());
或者只使用lambda:
coulours2.erase(remove_if(colours2.being(), colours2.end(),
[](const string& elem) { return elem == "purple"; },
coulours2.end());
答案 1 :(得分:2)
您根本不需要IsEqual
或任何自定义比较器。您不需要remove_if
变体,可以使用常规remove
。
colors.erase(std::remove(colors.begin(), colors.end(), "purple"), colors.end());