【问题标题】:C++ remove string from vector <algorithm> and <functional>C++ 从向量 <algorithm> 和 <functional> 中删除字符串
【发布时间】:2017-05-24 00:18:05
【问题描述】:

对于学校作业,我需要通过使用从矢量中删除紫色,这就是我想出的:

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 错误。应该如何正确使用?

【问题讨论】:

  • 有什么错误?你的minimal reproducible example 在哪里?还有please don't do cin.get() like that!
  • 你使用 remove_if + erase 错误。
  • 具体来说erase有多个版本。您使用的是在迭代器中擦除单个元素的那个,而不是擦除范围的那个。
  • 抱歉标题我更正了。我正在尝试从 colours2 中删除“紫色”。我怎么用错了 Jesprer Juhl?
  • IsEqual 会像 return s == s2; 一样简单。另外,为什么不只是std::equal

标签: c++ string functional-programming


【解决方案1】:

对于初学者,std::bind1ststd::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"));

正如 cmets 中提到的,您还使用了不正确的 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());

【讨论】:

    【解决方案2】:

    您根本不需要 IsEqual 或任何自定义比较器。你不需要remove_if 变体,你可以使用普通的remove

    colors.erase(std::remove(colors.begin(), colors.end(), "purple"), colors.end());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      相关资源
      最近更新 更多