Bogdan Bogdan - 10 months ago 58
C++ Question

Split vector to unique and duplicates c++

My goal is to split a vector into two parts: with unique values and with duplicates.

For example I have sorted

vector myVec=(1,1,3,4,4,7,7,8,9,9)
which should be split into
So myVecDuplicates contains all values that have duplicates while myVecUnique contains all values but in a single embodiment.

The order does not matter. My idea was to use unique as it splits a vector into two parts. But I have a problem running my code.

vector<int> myVec(8)={1,1,3,4,4,7,8,9};
vector<int>::iterator firstDuplicate=unique(myVec.begin(),myVec.end());
vector<int> myVecDuplicate=myVec(firstDuplicate,myVec.end());\\here error accures that says ' no match for call to '(std::vector<int>) (std::vector<int>::iterator&, std::vector<int>::iterator)'
vector<int> myVecUnique=myVec(myVec.begin()+firstDuplicate-1,myVec.end());

After running this code I get an error that says (2nd line) 'no match for call to '(std::vector) (std::vector::iterator&, std::vector::iterator)'

Please help me to understand the source of error or maybe suggest some more elegant and fast way to solve my problem (without hash tables)!

Answer Source

O(n) complexity solution:

#include <iostream>
#include <vector>

int main()
    std::vector<int> myVec = {1,1,3,4,4,7,7,8,9,9};
    std::vector<int> myVecDuplicatec;
    std::vector<int> myVecUnique;

    for(int &x : myVec)
        if(myVecUnique.size() == 0 || myVecUnique.back() != x)

    std::cout << "V = ";
    for(int &x : myVec)
        std::cout << x << ",";
    std::cout << std::endl << "U = ";
    for(int &x : myVecUnique)
        std::cout << x << ",";
    std::cout << std::endl << "D = ";
    for(int &x : myVecDuplicatec)
        std::cout << x << ",";