Compare two vectors C++

后端 未结 4 1154
忘掉有多难
忘掉有多难 2020-12-13 20:37

I was wondering is there any function to compare 2 string vectors to return the number of different(or the same) elements? Or i have to iterate over both of them and test it

4条回答
  •  长情又很酷
    2020-12-13 20:54

    I don't know of an existing function but writing one yourself shouldn't be too much trouble.

    int compare(const vector& left, const vector& right) {
      auto leftIt = left.begin();
      auto rightIt = right.begin();
      auto diff = 0;
      while (leftIt != left.end() && rightIt != right.end()) {
        if (*leftIt != *rightIt) {
          diff++;
        }
        leftIt++;
        rightIt++;
      }
    
      // Account for different length vector instances
      if (0 == diff && (leftIt != left.end() || rightIt != right.end())) {
        diff = 1;
      }
    
      return diff;
    }
    

    Notes

    • Omitted std:: prefix for brevity
    • This function needs to be updated if it should handle vector instances of different lengths

提交回复
热议问题