用于查找数组的独特成员的算法
Algorithm for finding unique members of array
我需要写一个简单的算法:
- 查找排序数组的独特成员
- 将这些成员放到另一个数组
- 计数唯一成员的数量
这是一个示例:
char array1[103] = {'V', 'U', 'A', 'A', 'U', 'U', 'A', 'A', 'V', 'U', 'A', 'V', 'V', 'U', 'U'};
char array2[10]; //Empty
//Output should be:
3
V U A
我需要在C 中写下它,但是PSEUODO代码也很棒。我可以自己编写代码,我只需要了解此算法。
- 创建一个空的
std::unordered_set
对象。一套是只有独特元素的集合。 - 循环通过输入数组,将元素添加到集合中。
- 完成后,将集合的元素复制到输出数组中。
以下可能会有所帮助:
#include <cassert>
#include <cstring>
#include <algorithm>
#include <iostream>
int main(int argc, char *argv[])
{
char array1[103] = {'V', 'U', 'A', 'A', 'U', 'U', 'A', 'A', 'V', 'U', 'A', 'V', 'V', 'U', 'U'};
char array2[10]; //Empty
int size = strlen(array1); // get the used size of the array
std::sort(std::begin(array1), array1 + size);
auto it = std::unique(std::begin(array1), array1 + size);
size = it - std::begin(array1);
assert(size < 10);
std::copy(std::begin(array1), it, std::begin(array2));
std::cout << size << std::endl;
for (int i = 0; i != size; ++i) {
std::cout << array2[i] << " ";
}
// Output is:
//3
//A U V
return 0;
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 通过指针算法访问结构数据成员
- 如何处理算法中具有不同名称成员函数的类?
- 算法在容器中查找具有给定值的元素之一的成员
- 为什么指向非静态成员函数的指针不能用作标准库算法的一元谓词
- 如何为涉及对象成员、间接寻址和强制转换的排序算法实现lambda函数
- 如何使用"is_member_function_pointer"在算法中包含/排除成员函数调用
- 用于查找数组的独特成员的算法
- 作为成员或非成员函数的算法
- STL算法无法访问私有成员
- 如何从函数模板类成员内的转换算法参数指向一元运算符函数
- 成员函数的实现:排序算法
- C++对对象的向量进行迭代,并将STL算法应用于成员变量
- 对STL算法进行专门化,以便在可用时自动调用高效的容器成员函数
- 以指向成员的指针作为比较器/"key"的 STD 算法
- 将c++成员函数指针传递给STL算法