0

I have a vector of a structure called ParsedFlag;

struct ParsedFlag {
    std::string flag, value;

    ParsedFlag init(std::string f, std::string v)
    {
        flag = f;
        value = v;

        return *this;
    }
}

Now, I have duplicate entries, which look like this:

(gay, yes)
(verbose, haha ok)
(desc, yeah okay)
(desc, yeah okay)
(a, 2)
(a, 2)
(c, c)
(f, f)
(g, 1)
(a, a)
(b, b)
(c, 1)

and my goal is to remove all of the duplicates of already existing ones: (desc, yeah okay), (a, 2).

How can I do this?

kernel_dev
  • 143
  • 1
  • 8
  • First of all I would implement the `==` compare operator in ParsedFlag. Then you should be able to use the std::vector::erase method – RoQuOTriX Aug 07 '20 at 06:33
  • 1
    There are various questions here on StackOverflow that target this problem. Like removing all duplicates while maintaining the sort order or removing the duplicates and sorting them. What is your problem with these solutions? – t.niese Aug 07 '20 at 06:40
  • 2
    Does this answer your question? [C++ how to remove duplicates from vector of Class type?](https://stackoverflow.com/questions/16404090/c-how-to-remove-duplicates-from-vector-of-class-type) – Lukas-T Aug 07 '20 at 07:50

1 Answers1

0

The easiest solution to the problem is to overload the "==" operator. What was done in step 1. Step 2 is for convenience only (overloading the "<<" operator for the cout method). Removing duplicates is done in step 3. By reloading the "==" operator, a simple for loop and the comparison of two iterators is enough.

#include <iostream>
#include <vector>
using namespace std;

struct ParsedFlag {
    std::string flag, value;

ParsedFlag init(std::string f, std::string v)
{
    flag = f;
    value = v;

    return *this;
}
};

//1)
inline bool operator==(const ParsedFlag& lhs, const ParsedFlag& rhs)
{
    return lhs.flag == rhs.flag and lhs.value == rhs.value;
}

//2
ostream& operator<<(ostream& os, const ParsedFlag& fl)
{
    os << fl.flag << ' ' << fl.value;
    return os;
}

int main() {
    std::vector<ParsedFlag> vec
    {
        {"gay", "yes"},
        {"gay", "yes"},
        {"verbose", "haha ok"},
        {"desc", "yeah okay"},
        {"desc", "yeah okay"}
    };
    
    for(const auto& fl : vec)
    {
        cout << fl << endl;
    }

    //3
    auto prev_it = vec.begin();
    for (auto it = vec.begin() + 1; it != vec.end(); ) 
    {
        if (*it == *prev_it)
        {
            it = vec.erase(it);
        } else 
        {
            ++it;
            ++prev_it;
        }
    }
    
    cout << "--- after---" <<endl;
    for(const auto& fl : vec)
    {
        cout << fl << endl;
    }
    return 0;
}

Another solution could be to use the std :: find_if function and a for_each loop

  • Providing a piece of code and a post script isn't called an answer. It should have sufficient information to understand what does that do, esp. the OP. – Rohan Bari Aug 08 '20 at 07:38