如何确定deque的元素是否具有两个以上相同的值

时间:2013-11-19 18:19:03

标签: c++ class deque

如果我有

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

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

有什么好方法可以找出elements_是否有两个以上至少有一个相同数字的元素?

例如:{1,0,0,6} {1,2,3,4} {4,2,3,1}每个都有数字1,所以check()将返回true。

1 个答案:

答案 0 :(得分:0)

vector相比,deque可能是更好的选择。直接的方法是检查第一个容器的每个元素是否在所有其他容器中出现:

myElement'容器般的'类:

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

myElements扩展程序:

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

测试:

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

当然可以进行优化。