C++编程实践

命名空间

为了解决函数不能重名的问题,就好比有两本一模一样的书,为了区分书是谁的在上面分别写上了不同的名字,而这个名字就是命名空间。
而c++中的输入是用流的方式实现的
键盘—>”hello”—>cin(输入流)—> >>(提取)—>变量—> <<(插入) —> cout(输出流)—>屏幕
while(cin >> a >>b )的意思是当a,b流都读完时,退出while循环,这样可以避免在C语言中scanf中必须要使用的%d,%c等占位符,当同时它也是有缺点的就是流式输入的算法效率极低,在大量输入时,并不推荐使用流式输入

#include<iostream>
#include<algorithm>

using namespace std;
const int maxn = 100+10;
int A[maxn];
int main()
{
    long long a,b;
    while(cin >> a >> b)
    {
        cout << min(a,b) << "\n";
    }
    return 0;
}

引用

在C++中,如果在参数前加上&,则表示这个参数按引用传递,在使用时输入相应的变量名即可
#include
using namespace std;

void swap2(int& a, int& b) {
int t = a; a = b; b = t;
}

int main() {
int a = 3, b = 4;
swap2(a, b);
cout << a << ” ” << b << “\n”;
return 0;
}
运行截图

字符串

C++特有类型string,但字符数组仍然有效,但不同点是string类型支持cin/cout的流式输出。而字符数组却不支持,string类型还可以直接相加

The First C++ Program

#include <iostream>

using namespace std;

int main()
{
    int number;
    cin>>number;
    cout << "My favorite name is "<<"源稚生呀" << endl;
    cout<<"my age is  "<<number<<endl;
    return 0;
}

运行截图:

再谈结构体

#include <iostream>
using namespace std;
struct Point {
    int x,y;
    Point(int x=0, int y=0)
    {
        this->x =x;
        this->y =y;
    }
    //:x(x),y(y){};为简式写法
};
Point operator + (const Point& A,const Point& B)
{
    return Point(A.x+B.x,A.y+B.y);
}
ostream& operator << (ostream &out, const Point& p) {
out << "(" << p.x << "," << p.y << ")";
return out;
}
int main()
{
   Point a,b(2,3);
   a.y = 4;
   cout<<a+b<<endl;
   return 0;
}

这里写图片描述
1. 结构体中定义的函数没有返回值,这样的函数被称为构造函数
2. this为指向当前对象的指针,this->x为当前的对象X
3. 程序实现的是结构体的加法,在程序后面重新定义了加法

STL初步(标准模板库)

排序与检索

现有N个大理石,每个大理石上写了一个非负整数。首先把各数从小到大排序,然后回
答Q个问题。每个问题问是否有一个大理石写着某个整数x,如果是,还要回答哪个大理石上
写着x。排序后的大理石从左到右编号为1~N。(在样例中,为了节约篇幅,所有大理石上
的数合并到一行,所有问题也合并到一行。

#include <iostream>

using namespace std;
struct Point {
    int x,y;
    Point(int x=0, int y=0)
    {
        this->x =x;
        this->y =y;
    }
    //:x(x),y(y){};为简式写法

};
Point operator + (const Point& A,const Point& B)
{
    return Point(A.x+B.x,A.y+B.y);
}
ostream& operator << (ostream &out, const Point& p) {
out << "(" << p.x << "," << p.y << ")";
return out;
}


int main()
{
   Point a,b(2,3);
   a.y = 4;
   cout<<a+b<<endl;
   return 0;
}

运行截图,简化了一下,没有N个问题

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值