C++ C++;从向量中删除字符串<;算法>;及<;功能性>;
对于学校作业,我需要使用从向量中删除紫色,这是我想到的:C++ C++;从向量中删除字符串<;算法>;及<;功能性>;,c++,string,functional-programming,C++,String,Functional Programming,对于学校作业,我需要使用从向量中删除紫色,这是我想到的: bool IsEqual(string s, string s2) { if (s == s2) { return true; } } int main() { vector<string> coulours2 = { "red", "green", "blue", "orange", "purple", "orange", "black", "green" }; ve
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;
}
bool IsEqual(字符串s、字符串s2)
{
如果(s==s2)
{
返回true;
}
}
int main(){
向量coulours2={“红色”、“绿色”、“蓝色”、“橙色”、“紫色”、“橙色”、“黑色”、“绿色”};
向量::迭代器newEnd;
newEnd=remove_if(coulours2.begin(),coulours2.end(),bind2nd(等相等,“紫色”);
颜色2.擦除(新结束);
cin.get();
返回0;
}
但是我犯了很多错误,我想我用错了。我应该如何正确使用它?对于初学者来说,
std::bind1st
和std::bind2nd
函数不推荐使用。应该考虑使用<代码> STD::Boe< /Cord>,它更通用,更易于使用。
如果确实要使用bind2nd
,则传入的函数必须是可调整函数,即导出一些额外类型信息的函数对象类型。要将原始函数指针转换为自适应函数,请使用名称有趣的ptr\u 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"));
使用std::bind执行此操作的“更好”方法如下所示:
using namespace std::placeholders;
coulours2.erase(remove_if(coulours2.begin(), coulours2.end(),
bind(equal_to<string>(), _1, "purple")),
coulours2.end());
对于初学者来说,std::bind1st
和std::bind2nd
函数是不推荐使用的。应该考虑使用<代码> STD::Boe< /Cord>,它更通用,更易于使用。
如果确实要使用bind2nd
,则传入的函数必须是可调整函数,即导出一些额外类型信息的函数对象类型。要将原始函数指针转换为自适应函数,请使用名称有趣的ptr\u 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"));
使用std::bind执行此操作的“更好”方法如下所示:
using namespace std::placeholders;
coulours2.erase(remove_if(coulours2.begin(), coulours2.end(),
bind(equal_to<string>(), _1, "purple")),
coulours2.end());
您根本不需要IsEqual
,也不需要任何自定义比较器。您不需要remove\u如果变量,您可以使用常规remove
colors.erase(std::remove(colors.begin(), colors.end(), "purple"), colors.end());
您根本不需要IsEqual
,也不需要任何自定义比较器。您不需要remove\u如果变量,您可以使用常规remove
colors.erase(std::remove(colors.begin(), colors.end(), "purple"), colors.end());
错误是什么?你的房间在哪里?和如果
+擦除
错误,则使用的是remove\u。具体来说,存在多个版本的。您使用的是在迭代器中擦除单个元素的元素,而不是擦除范围的元素。很抱歉,我更正了标题。我正在尝试从颜色2中去掉“紫色”。我怎么会用错Jesprer Juhl?IsEqual
会更简单,因为它只返回s==s2代码>。还有,为什么不干脆std::equal
?错误是什么?你的房间在哪里?和如果
+擦除
错误,则使用的是remove\u。具体来说,存在多个版本的。您使用的是在迭代器中擦除单个元素的元素,而不是擦除范围的元素。很抱歉,我更正了标题。我正在尝试从颜色2中去掉“紫色”。我怎么会用错Jesprer Juhl?IsEqual
会更简单,因为它只返回s==s2代码>。还有,为什么不干脆std::equal
?