STL:仅保留唯一的字符串字符并保留顺序

问题描述 投票:0回答:1

std::set
std::unordered_set
上的
string
都只提取唯一字符,但都不按字符串中出现的原始顺序保留字符。

我对 STL 的很多内容一无所知,但我想知道是否有一种 STL 方法可以从字符串中获取唯一的字符,而不丢失原始顺序,也不诉诸循环。我可以使用迭代器、循环以及例如

std::remove
来完成此操作,但我想知道是否有更优雅的方法。这个思维列车是由今天的 GeeksforGeeks 问题触发的,因此测试字符串是
"geEksforGEeks"
,最终应该为
"geEksforG"
(区分大小写,
'g' != 'G'
)。

想法?

c++ stl unique
1个回答
0
投票

会有很多选项,比如使用 std::remove_if,或者在本例中使用 std::copy_if

#include <string>
#include <array>
#include <algorithm>
#include <iostream>

std::string without_duplicates(const std::string& input)
{
    std::array<bool,256ul> seen{}; // initialize all "seen" characters to false
    std::string output;

    // std::back_inserter allows you to copy to an "empty" collection by adding elements at the end
    // copy_if takes a lambda expression which will be called for each character in the input string.
    std::copy_if(input.begin(),input.end(),std::back_inserter<std::string>(output),[&](const char c)
    {
        bool copy_to_output_string = !seen[c];
        seen[c] = true;
        return copy_to_output_string;
    });

    return output;
}

int main()
{
    auto result = without_duplicates("geEksforGEeks");
    std::cout << result;
}
© www.soinside.com 2019 - 2024. All rights reserved.