创建一个没有重复项的数组

Creating an array without duplicates

本文关键字:数组 一个 创建      更新时间:2023-10-16

我的问题如下。如何创建一个数组,其中包含 const char * 中使用的所有字符,以使数组没有任何重复项。例如:

const char *pass = "Qqqqqqqwwwww11111" 

应该创建一个数组

Q  |  q  |  w  |  1

变量传递由用户给出,因此很难确定它的外观。

许多解决方案之一是使用 std::sortstd::unique 。使用std::string也更简单更安全(或std::vector,...

#include <iostream>
#include <algorithm>
int main() {
    char *pass = "Qqqqqqqwwwww11111"; // or by user input
    // using std::string is easier and safer (works similarly with std::vector)
    std::string data(pass);
    // Remove duplicates with std::sort and std::unique
    std::sort(data.begin(), data.end());
    auto end = std::unique(data.begin(), data.end());
    // Remove duplicates – if needed.
    data.erase(end, data.end());
    // Print the unique chars
    std::cout << data << std::endl;
    return 0;
}

根据您正在执行的操作,您可能不需要erase data 的重复元素。在这种情况下,请记住end是第一个重复元素的迭代器(或者,如果数据首先没有重复,则等于 data.end() )。

注意:在使用std::unique之前,您绝对需要对数据进行排序。

在这里你可以试试这个代码

如果您的意思是创建一个没有相邻重复元素的数组,那么首先您应该计算字符串传递中有多少唯一元素,然后动态为数组分配内存并复制其中的唯一元素。该任务可以通过使用标准算法简单地完成。例如

char *a = 0;
size_t n = std::strlen( pass );
if ( n != 0 )
{
    size_t count = 1 + std::inner_product( pass + 1, pass + n, pass, 0u, 
                                           std::plus<size_t>(),
                                           std::not_equal_to<const char>() );
    a = new char[count + 1];
    std::unique_copy( pass, pass + n + 1, a );
}

或者也许写起来会更简单

char *a = 0;
size_t n = 1 + std::strlen( pass );
size_t count = 1 + std::inner_product( pass + 1, pass + n, pass, 0u, 
                                       std::plus<size_t>(),
                                       std::not_equal_to<const char>() );
a = new char[count];
std::unique_copy( pass, pass + n, a );

我了解,您想删除所有重复项并且顺序是无能为力的,因此std::unique是不够的。

虽然您的元素类型很小,例如char - 您可以使用 array/std::vector/std::bitset 来记住以前满足过哪些元素:

现场演示

template<typename I, typename O>
I remove_duplicates(I first, I last, O out)
{
    using T = typename iterator_traits<I>::value_type;
    using limits = numeric_limits<T>;
    constexpr auto min = limits::lowest();
    constexpr auto max = limits::max();
    bitset<size_t(max - min) + 1> had_before;
    while(first != last)
    {
        T x = *first;
        size_t i = x - min;
        if(!had_before[i])
        {
            had_before.set(i);
            *out = x;
            ++out;
        }
        ++first;
    }
    return out;
}
int main()
{
    char s[] = "Qqqqqqqwwwww111qq1q1Qa";
    auto first = begin(s), last = end(s);
    auto new_last = remove_duplicates(first, last, first);
    for_each(first, new_last, [](char x) { cout << x; });
}

输出为:

Qqw1a
相关文章: