博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++ 结构体初始化
阅读量:6996 次
发布时间:2019-06-27

本文共 1682 字,大约阅读时间需要 5 分钟。

  结构体是C++常用的数据结构,其初始化可以如下:

#include
using namespace std;struct Node{ int M, V; Node(int a, int b){ M = a; V = b; }};int main(){ Node n1(1, 65), n2(5, 23), n3(2, 99); cout << n1.M << ' ' << n1.V << endl; cout << n2.M << ' ' << n2.V << endl; cout << n3.M << ' ' << n3.V << endl; }

   此外,结构体还可以重载操作符,如:

#include
using namespace std;struct Node{ int M, V; Node(int a, int b){ M = a; V = b; } friend bool operator < (const Node n1, const Node n2){ return n1.V < n2.V; } friend bool operator > (const Node n1, const Node n2){ return n1.V > n2.V; } friend ostream &operator << (ostream &os, const Node n){ os << n.M << ' ' << n.V; return os; }};int main(){ Node n1(1, 65), n2(5, 23), n3(2, 99); if(n1 < n2) cout << n1 << endl; else cout << n2 << endl;}

   自然,结构体也可以配合STL一起使用,如配合优先队列使用,注意在只用有优先队列是必须重载小于号,只重载大于号是不可以的:

#include
using namespace std;struct Node{ int M, V; Node(int a, int b){ M = a; V = b; } friend bool operator < (const Node n1, const Node n2){ return n1.V < n2.V; } friend bool operator > (const Node n1, const Node n2){ return n1.V > n2.V; } friend ostream &operator << (ostream &os, const Node n){ os << n.M << ' ' << n.V; return os; }};int main(){ Node n1(1, 65), n2(5, 23), n3(2, 99); priority_queue
pq; pq.push(n1), pq.push(n2), pq.push(n3); while(!pq.empty()){ Node n = pq.top(); pq.pop(); cout << n << endl; }}

 

转载于:https://www.cnblogs.com/Vincent-Bryan/p/6622790.html

你可能感兴趣的文章
回溯算法实践--工作分配问题
查看>>
java command line error opening registry key 'Software\JavaSoft\Java Runtime Environment' java.dll
查看>>
C#串口通信总结
查看>>
day22 Pythonpython 本文sys模块
查看>>
Java中String类通过new创建与直接赋值的区别
查看>>
常用的PHP数据库操作方法(MYSQL版)
查看>>
和最大子序列(贪心)
查看>>
深入学习golang(1)—数组与切片
查看>>
[ARC055D]隠された等差数列
查看>>
A trip through the Graphics Pipeline 2011_04
查看>>
程序锁的分析一
查看>>
偶尔遇到的“The request was aborted:Could not create SSL/TLS secure channel.”怎么解决?
查看>>
团队作业3——需求分析与设计
查看>>
几大搜索引擎的网站登录入口
查看>>
Java 二维码--转载
查看>>
stopImmediatePropagation的应用
查看>>
ArcEngine唯一值着色再开发!
查看>>
K-means &K-medoids 聚类
查看>>
MySQL配置文件my.cnf优化详解
查看>>
MySQL完整性约束
查看>>