There's a standard algorithm std::unique_copy that does exactly this:
auto end = std::unique_copy(std::begin(array), std::end(array), array2);
The returned iterator end
points to one past the last element that is inserted into array2
, so you can calculate the number of unique elements that were copied like this:
auto num = std::distance(array2, end);
I would recommend using std::vector
instead of arrays anyway, and then you don't have to worry about computing the number of copied unique elements. In case you use a vector
the 3rd argument to the algorihtm would be std::back_inserter(vec)
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…