C++结构问题

C++ structure issue

下面这部分的作用是什么?

bool operator < ( const edge& p ) const 
{
    return w < p.w;
}

我在这里给出了完整的代码(我不知道是否有必要粘贴整个代码)。我只是不明白结构部分。 我搜索了几个资源,但没有任何简单性。

struct edge
{
    int u,v,w;
    bool operator < ( const edge& p ) const 
    {
        return w < p.w;
    }
};

int pr[MAXN];
vector<edge>e;

int find(int r)
{
    return (pr[r]==r) ? r:  find(pr[r]);
}

int mst(int n)
{
    sort(e.begin(),e.end());
    for(int i=1;i<=n;i++)pr[i]=i;

    int count=0,s=0;
    for(int i=0;i<(int)e.size();i++)
    {
        int u=find(e[i].u);
        int v=find(e[i].v);
        if(u!=v)
        {
            pr[u]=v;
            count++;
            s+=e[i].w;
            if(count==n-1) break;
        }
    }
    return s;
}

int main(){
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int u,v,w;
        cin>>u>>v>>w;
        edge get;
        get.u=u; get.v=v; get.w=w;
        e.push_back(get);
    }
    cout<<mst(n)<<endl;
    return 0;

}

想想你什么时候做 1 < 3。 1 显然小于 3。好吧,但是假设你有这个 struct/class/union(注意 3 在 C++ 中几乎是一样的东西)叫做 Toy

struct Toy
{
  float _volume;
  float _weight;
  std::string _brand;
};

现在实例化 2 个 Toy 对象:

Toy car, kite;
car._volume = 27000.0; //27000 cm^3
car._weight = 150.0; //150 grams

kite._volume = 10000; //10000 cm^3
kite._weight = 200.0; // 200 grams

if (kite < car){
  std::cout << "car!"; // is toy car bigger!?
}else{
  std::cout << "kite!"; // or is it the kite?
}

现在,当你检查风筝是否比玩具车 smaller 时,C++ 语言不知道你的意思。可能是您想查看哪个重量更轻,也可能是您正在检查哪个重量更轻space;体积更小。为了解决歧义,C++ 要求程序员为您的自定义对象实现运算符。

如果我们去掉很多算子设计中的syntactic sugar部分,让它小于(<)为了例子,a < b就变成了a.operator<(b).所以 operator< 可以说是一个 class/struct/union 方法,和其他方法一样!

为了清除玩具示例中的歧义,我们 re-implement/overload 我们结构的 operator<() 方法让它比较体积如下:

struct Toy
{
  float _volume;
  float _weight;
  std::string _brand;
  bool operator<(const Toy & otherToy)
  {
    return _volume < otherToy._volume; // or ._weight for each if we want to compare by weight
  }
};

if (kite < car){
  std::cout << "car!"; // the car has more volume!
}else{
  std::cout << "kite!";
}

通过您的代码片段,您可以看到 edge 对象比较标准在 operator< definition 中定义为成员 w。因此,与该运算符相比,w 较小的对象是较小的对象。