[英]How can I implement the behavior of unique in matlab using C++?
In Matlab, the [C, ia, ic] = unique(A)
function returns an sorted array C
in which the duplicates in A
are removed, and the ia
and ic
arrays contains the indices such that C = A(ia) and A = C(ic)
。 例如:
A = [1, 2, 3, -1, -2, 0, 0, 0, 4];
[C, ia, ic] = unique(A);
C = [-2, -1, 0, 1, 2, 3, 4];
% The indices are incremented by 1 to accomodate the C++ convection.
ia = [4, 3, 7, 0, 1, 2, 8]; % size(ia) = size(C)
ic = [3, 4, 5, 1, 0, 2, 2, 2, 6]; % size(ic) = size(A)
这是我的实现:
std::vector<int> A = {1, 2, 3, -1, -2, 0, 0, 0, 4};
std::set<int> C(A.begin(), A.end());
std::vector<int> ic;
ic.reserve(A.size());
std::transform(A.begin(), A.end(), std::back_inserter(ic),
[&](int x) { return (std::distance(C.begin(), C.find(x))); });
我现在可以正确获取数组 C 和 ic,但我不知道如何获取数组 ia。
有人可以帮我弄这个吗?
答案与您计算ic
的方式非常相似。 只需在transform
调用中交换A
和C
:
std::vector<int> ia;
ia.reserve(C.size());
std::transform(C.begin(), C.end(),
std::back_inserter(ia),
[&](int x) { return std::distance(A.begin(),
std::find(A.begin(), A.end(), x));
});
您还需要使用std::find
,因为std::vector
不提供.find()
成员 function。
另一种在语法上与您的 Matlab 类似的方法:
#include <algorithm>
#include <vector>
std::vector<int> A = {1, 2, 3, -1, -2, 0, 0, 0, 4};
std::vector<int> B (A.begin(), A.end());
std::sort(B.begin(), B.end());
auto last = std::unique(B.begin(), B.end());
B.erase(last, B.end());
如果要查找条目位置的索引,可以使用find_first_of
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.