gpt4 book ai didi

c++ - 删除字符串中最后一次出现的重复字符

转载 作者:行者123 更新时间:2023-12-04 07:32:31 28 4
gpt4 key购买 nike

我怎样才能删除其余的字符?

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
}
Try it on godbolt.org

关于c++ - 删除字符串中最后一次出现的重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67881174/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com