0

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). For example:

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) 

Here is my implementation:

  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))); });

I now can correctly get the array C and ic, but I don't know how to get the array ia.

Can someone help me with this?

2 Answers 2

3

The answer is very similar to how you calculate ic. Just swap A and C in the transform call:

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)); 
});

You also need to use std::find since std::vector doesn't provide a .find() member function.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried this but the STL doesn't provide a find member function for std::vector.
Aah, right, you'll need std::find. Edited the answer.
3

Another approach which is similar in syntax to your 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()); 

Compiler explorer link

If you want to find the indices for the locations of entries, you can use find_first_of.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.