【发布时间】:2021-06-08 03:51:04
【问题描述】:
我怎样才能删除剩下的字符?
s.erase(std::unique(s.begin(), s.end()), s.end());
这只会删除重复的字符,不会删除第一次出现的字符。
示例:"Hello World"
将返回"he wrd"
【问题讨论】:
我怎样才能删除剩下的字符?
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
}
【讨论】:
据我了解,如果它有重复项(其计数大于2),您想要remove all occurrences of a character from a string,并且删除不区分大小写(意味着H 将被视为h) .
因此,您可以创建所有字符的频率图,如果其计数为 >1,则使用 erase() 删除其所有出现:
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
int main()
{
string x; getline(cin, x);
map<char, int> freq;
for (size_t i = 0; i < x.size(); i++)
{
x[i] = tolower(x[i]); //lowercase all the character
freq[x[i]]++; //frequency of character
}
x.erase(remove_if(x.begin(), x.end(),
[&] (const char& c) { return freq[c] > 1; }),
x.end());
cout << x;
}
输出:
Hello world
he wrd
另一个例子:
ABbcDdDEfF
ace
【讨论】: