C++ C++;结构问题
下面这部分的功能是什么C++ C++;结构问题,c++,c++11,struct,graph-theory,C++,C++11,Struct,Graph Theory,下面这部分的功能是什么 bool operator < ( const edge& p ) const { return w < p.w; } bool运算符>v>>w; 边缘获取; get.u=u;get.v=v;get.w=w; e、 推回(得到); } 当你做1
bool operator < ( const edge& p ) const
{
return w < p.w;
}
bool运算符<(常数边&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;
}
struct-edge
{
国际u,v,w;
布尔运算符<(常数边和p)常数
{
返回w>m;
对于(inti=1;i>u>>v>>w;
边缘获取;
get.u=u;get.v=v;get.w=w;
e、 推回(得到);
}
当你做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?
}
通过您的代码片段,您可以看到,edge
对象比较标准在operatorw
。因此,与该操作符相比,无论哪个w
较小的对象都是较小的对象。您不明白struct edge
定义的哪一部分?“需要解释”不是一个实际问题。请在帖子中提出一个实际有答案的特定问题。Google“运算符重载”。c++结构更像是一个c++类,而不是一个c-结构。你的结构有3个整数。(非虚拟)方法不应影响sizeof(edge)。编译器还提供了几种方法,如ctor和dtor以及其他一些方法(因为您没有禁止它们)。我不理解结构中的运算符重载部分。我以前没有使用过它。是的,解释很好,很简单。我现在明白了,谢谢@Aiman
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!";
}