c++ - 删除字符串中最后一次出现的重复字符
问题描述
我怎样才能删除其余的字符?
s.erase(std::unique(s.begin(), s.end()), s.end());
这只会删除重复的字符,不会删除第一次出现的字符。
示例:"Hello World"
将返回"he wrd"
解决方案
此函数没有内置函数,但您可以编写自己的通用算法来完成此操作:
#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>
template <class C>
auto erase_if_duplicate(C& c)
{
using T = typename C::value_type;
const auto begin = c.begin();
const auto end = c.end();
std::unordered_map<T, std::size_t> count{};
std::for_each(
begin, end,
[&] (const T& v) { ++count[v]; });
const auto it = std::remove_if(
begin, end,
[&] (const T& v) { return count.at(v) > 1; });
return c.erase(it, end);
}
int main()
{
// example usage
std::string s{"hello world"};
erase_if_duplicate(s);
std::cout << s; // he wrd
}
推荐阅读
- .net - .Net Core / Angular 6 - Access-Control-Allow-Origin 不允许来源
- javascript - 如何使用 ajax 和 mysql 遍历数据
- c - 用 C 写一个 shell 我的程序无法退出()
- python - error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools" scrapy
- java - Java FileDialog browse and read from file
- android - GPS跟踪系统?
- python - 如何在python中获取属性的setter方法的属性
- c - 源路径中有空格时 VS Code 调试失败
- python - Any way to read number of active workers of gunicorn managed by the arbiter from command line?
- c++ - Access static variable from CPP file to other header file