【问题标题】:replace_if in string to replacereplace_if 在要替换的字符串中
【发布时间】:2017-05-19 16:58:14
【问题描述】:

我正在使用 replace_if 解决一个简单的问题,但每次它都会给我错误。 问题
在给定字符串中删除相邻字符并使字符串尽可能紧凑。
例如: aabcc 将变为 b,aabbcc 将变为空字符串。

int main()
{
    string s;
    cin>>s;    
    replace_if(s.begin(),s.end(),[](char l, char r){return l == r;},"");
    cout << string(s.begin(),s.end());   
    return 0;
}

错误:

/usr/include/c++/6/bits/stl_algo.h:4280:12: note:   candidate expects 3 arguments, 2 provided  
solution.cc:19:51: note: candidate:  
main()::<lambda(char, char)> 
replace_if(s.begin(),s.end(),[](char l, char r){

【问题讨论】:

  • 您遇到什么错误?你读过documentation of replace_if吗?
  • 是的,阅读文档但无法理解..
  • @InvI std::replace_if 无法更改字符串的大小,它只能将元素从一个值更改为另一个值。寻找另一种方法。
  • 如果您遵循此处的指南,这将对每个人都有帮助:stackoverflow.com/help/mcve
  • 为什么要尝试使用名称中带有replace 的算法来删除元素?

标签: c++ string c++11 lambda


【解决方案1】:

std::replace_if 对特定类型的值序列(在您的情况下为char 类型)进行操作,可用于检查序列中的每个值并可能将其替换为相同类型的另一个值.换句话说,如果允许您将所有as 替换为bs,但不允许删除元素或将谓词基于被检查元素本身之外的更多内容。

你需要的是更复杂的组合,但可以完成,例如像这样:

auto it = s.begin();
for (;;)
{
  it = std::adjacent_find(it, s.end()); // Find two adjacent same characters
  if (it == s.end()) // If there are none, we're done
    break;
  auto next = std::find_if(it, s.end(), [it](char c) { return c != *it; }); // Find next different character
  it = s.erase(it, next); // Erase all in range [it, next)
}

【讨论】:

  • 我认为没有算法的循环会更简单、更易读、更高效
  • @Slava 我不同意,因为跟踪相邻的索引/迭代器很容易出错。就效率而言,我认为它是相同的:毕竟这只是一次迭代。
猜你喜欢
  • 1970-01-01
  • 2012-04-26
  • 1970-01-01
  • 1970-01-01
  • 2017-03-06
  • 2011-12-17
  • 2020-03-08
相关资源
最近更新 更多