【问题标题】:Vector iterator comparison向量迭代器比较
【发布时间】:2012-03-28 13:09:19
【问题描述】:

比较两个向量中的值时遇到问题。

以下是我的程序的示例代码:

  template <typename T> bool CompareVectors(std::vector<T> vector1, std::vector<T> vector2)
  {
    std::sort(vector1.begin(),vector1.end());
    std::sort(vector2.begin(),vector2.end());
    if (vector1.size() != vector2.size())
      return false;
    else
    {
      bool found = false;
      std::vector<T>::iterator it;
      std::vector<T>::iterator it2;
      for (it = vector1.begin();it != vector1.end(); it++)
      {      
        for(it2 = vector2.begin(); it2 != vector2.end(); it2++)
        {
          if(it == it2) // here i have to check the values in the itearators are equal.
          {
            found = true;
            break;
          }
        }
        if(!found)
          return false;
        else
          found = false;
      }
      return true;  
    }
    };

在这个示例代码中,我必须比较两个向量。为此,我使用std::sort() 对这两个向量进行了排序。由于向量中的数据类型是模板(我在向量中使用类对象),std::sort() 无法正常工作。即,有时两个向量在排序后给出不同的元素顺序。

所以我也不能使用std::equal() 函数。

对于另一种解决方案,我为 twi 向量使用了两个迭代器。

并迭代一个向量并在另一个向量中搜索该元素。为此,迭代器比较无法使用。

【问题讨论】:

  • 你是如何实现operator&lt; 的排序的?这可能是你的问题......我敢打赌你有一个指针向量,并且你的项目按它们的地址而不是它们的值排序。
  • 您是否为正在使用的类定义了&lt;== 运算符?
  • yaa 我已经为我正在使用的类定义了==、

标签: c++ vector iterator comparison


【解决方案1】:

首先你必须在这里使用typename关键字:

typename std::vector<T>::iterator it;
typename std::vector<T>::iterator it2;

没有typename,您的代码甚至无法编译。

要比较迭代器指向的,你必须这样做:

if( *it == *it2)

你可以把比较函数写成:

//changed the name from CompareVectors() to equal()
template <typename T> 
bool equal(std::vector<T> v1, std::vector<T> v2)
{
  std::sort(v1.begin(),v1.end());
  std::sort(v2.begin(),v2.end());
  if ( v1.size() != v2.size() )
       return false;
  return std::equal(v1.begin(),v1.end(), v2.begin());
};

【讨论】:

  • 你可以简单地说return v1 == v2;而不是测试大小然后调用std::equal
  • @Blastfurnace:很好。我不知道存在== 非成员函数来测试两个向量的相等性。
【解决方案2】:

应该这行:

if(it == it2)

if (*it == *it2)

第一行是比较指针而不是值。

【讨论】:

    【解决方案3】:

    这里有多个问题。首先,您说std::sort() 不起作用。您是否为您的班级重载了operator&lt;

    此外,您需要比较迭代器 指向 的对象:

    *it == *it2
    

    此外,您需要同时遍历两个数组(只需一个循环):

    for (it = vector1.begin(), it2 = vector2.begin();
         it != vector1.end(), it2 != vector2.end();
         it++, it2++) {
      ...
    }
    

    虽然真的,你应该通过重载operator== 来使用std::equal()

    从效率的角度来看,您应该比较size() 的值您对数组进行排序之前。

    【讨论】:

      猜你喜欢
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 2012-11-17
      • 2013-04-29
      • 2017-05-02
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      相关资源
      最近更新 更多