首页 > 解决方案 > 删除字符串中最后一次出现的重复字符

问题描述

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

s.erase(std::unique(s.begin(), s.end()), s.end());

这只会删除重复的字符,不会删除第一次出现的字符。
示例:"Hello World" 将返回"he wrd"

标签: c++c++17

解决方案


此函数没有内置函数,但您可以编写自己的通用算法来完成此操作:

#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
}

在 godbolt.org 上试试


推荐阅读