【问题标题】:How to understand C++ error, "no match for 'operator==' (operand types are 'std::pair' and 'const int')"?如何理解 C++ 错误,“'operator==' 不匹配(操作数类型为 'std::pair' 和 'const int')”?
【发布时间】:2017-10-13 11:00:15
【问题描述】:

我正在代码块上编译以下代码,并收到以下错误声明

C:\Program Files (x86)\CodeBlocks\MinGW\lib\gcc\mingw32\4.9.2\include\c++\bits\predefined_ops.h|191|错误:'operator==' 不匹配(操作数类型是 'std::pair' 和 'const int')

头文件predefined_ops.h中同样显示错误:

template<typename _Iterator>
    bool
    operator()(_Iterator __it)
    { return *__it == _M_value; }//error
    };

这是我正在编译的代码

#include <bits/stdc++.h>
using namespace std;
class Soham
{
    int *a,n;
    map<int,int> m;
public:
    Soham(int x);
    void search1(int,int,int,int);
};
Soham::Soham(int x)
{
    n=x;
    a=new int[n];
    for(int i=0;i<n;i++)
        cin>>a[i];
    for(int i=0;i<n;i++)
    {
        for(int j=i+1;j<n;j++)
        {
            if(abs(a[i]-a[j])<=1)
               {
                   search1(a[i],a[j],i,j);
               }
        }
    }
    map<int,int> ::iterator it1;
    for(it1=m.begin();it1!=m.end();it1++)
    {
        cout<<it1->first<<"-->"<<it1->second<<endl;
    }
}
void Soham::search1(int x,int y,int i1,int j1)
{
    if(m.empty())
    {
        m.insert(std::pair<int,int>(x,i1));
        m.insert(std::pair<int,int>(y,j1));
    }
    else
    {
       map<int,int>::iterator it,it1;
       it=find(m.begin(),m.end(),x);
       it1=find(m.begin(),m.end(),y);
       if(it!=m.end()|| it1!=m.end())
       {

           if (it!=m.end() && it->second!=i1)//chance of error 
              {
                    m.insert(std::pair<int,int>(it->first,i1));
              }


              if(it1!=m.end() && it1->second!=j1)//chance of error
            {
                    m.insert(std::pair<int,int>(it1->first,j1));
            }


       }
        //find failed to find element in the map how to show this particular condition
        else  //error
        {
            if(it!=m.end())
            {
                m.insert(std::pair<int,int>(x,i1));
            }
            if(it1!=m.end())
            {
                m.insert(std::pair<int,int>(y,j1));
            }

        }
    }

}
int main()
{
    int n;
    cin>>n;
    Soham a(n);
    return 0;
}

根据错误声明,我正在使用 == 运算符进行无效比较,但我不明白 这是最有可能在以下情况下发生错误的地方

 if (it!=m.end() && it->second!=i1)
 if(it1!=m.end() && it1->second!=j1)

在第二次检查中,我正在检查 pair(it->second) 的第二个元素,它是 int 类型的整数变量 i1 那么为什么 == 运算符会发生错误。如果不是这样,我可能以错误的方式理解了错误并相应地解释了我的理解。什么产生了错误以及如何纠正它?

【问题讨论】:

  • 如果您遵循错误消息的“链”(他们可能会说“...从...实例化”),编译器最终应该会告诉您问题出在find 行。在最好的情况下,导航模板错误消息可能具有挑战性。

标签: c++ operators


【解决方案1】:

更改以下行,它将运行

  //it=find(m.begin(),m.end(),x);
  it = m.find(x);
  //it1=find(m.begin(),m.end(),y);
  it1 = m.find(y);

基本上你必须使用find 成员函数而不是 find算法。

【讨论】:

  • 感谢 Partha 澄清问题:)
猜你喜欢
  • 2020-11-29
  • 2023-04-09
  • 2023-04-07
  • 2021-04-20
  • 2016-12-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2019-09-05
相关资源
最近更新 更多