Search code examples
c++classdeque

How to find out if deque's element has more than two same values


If I have

class myElement{
public:
int get_first();
int get_second();
int get_third();
int get_fourth();

private:
deque<int> numbers_ = {1, 2, 3, 4} // numbers are different in every element
};

and

class myElements{
public:
bool check(); // checks if theres more than two elements that contains the same number
private:
deque<myElement> elements_;
};

What would be a good way to find out if elements_ has more than two elements with atleast one same number?

for example: {1, 0, 0, 6} {1, 2, 3, 4} {4, 2, 3, 1} each of those have number 1 so check() would return true.


Solution

  • Probably, a vector is a better choice here than a deque. The straightforward way would be to check for each element of the first container if it occurs in all other containers:

    The myElement 'container-like' class:

    using namespace std;
    
    class myElement{
    public:
        bool contains(int n) const {
          return find(numbers_.begin(), numbers_.end(), n) != numbers_.end();
        }
        myElement(std::vector<int> ns):numbers_(ns){}
        vector<int> values() const { return numbers_; }
    private:
        vector<int> numbers_;// = {1, 2, 3, 4} // numbers are different in every element
    };
    

    The myElements extensions:

    class myElements{
    public:
        myElements(initializer_list<myElement>&& t): elements_(t){}
        bool check() {
          myElement& first = elements_.front();
    
          for ( auto n: first.values()) {
             if (occurs_in_each_but_first(n)) {
                return true;
             }
          }
          return false;
        }
    
    private:
    
        bool occurs_in_each_but_first(int n) {
          auto it = begin(elements_);
          ++it;
          auto itEnd = end(elements_);
          for (; it != itEnd; ++it) {
             if (! it->contains(n)) return false;
          }
          return true;
        }
    
        vector<myElement> elements_;
    };
    

    A test:

    #include <cassert>
    void main(){
      myElement e0({11,12,13,4});
      myElement e1({11,12,13,41});
      myElement e2({1,2,3,4});
      myElement e3({1,2,3,4});
      myElement e4({1,22,23,24});
    
      assert(myElements({e0,e2,e3}).check());
      assert(!myElements({e1,e2,e3}).check());
      assert(myElements({e2,e3,e4}).check());
    }
    

    Where optimizations are possible, of course.