引用类型和指针

时间:2020-12-23 16:15:23
三个整数a,b,c从小到大排序

题目描述

输入三个整数a,b,c;按照从小到大次序输出。 

输入

输出

样例输入

1 2 3
3 2 1
6 6 6
100 10 1

样例输出

1 2 3
1 2 3
6 6 6
1 10 100

#include <iostream>
#include <cstring> 
#include<algorithm>
using namespace std;
void swap2(int& a,int& b)
{
	int t=a;a=b;b=t;
}
int main()
{
	int a,b,c,t;
    while(cin>>a>>b>>c)
    {
	    if(a>b) swap2(a,b);
	    if(a>c) swap2(a,c);
	    if(b>c) swap2(b,c);
	    cout<<a<<" "<<b<<" "<<c<<endl;		
	}
	return 0;
}


指针是一种特殊的对象,指针的类型是它所指向对象的类型,它的值是它所指向对象的地址值。
例如:
int *p1;      //定义一个指向int型的指针p1 
char *p2;  //定义一个指向char型的指针p2
float *p3;  //定义一个指向float型的指针p3

 引用,就是给对象起一个别名,使用该别名可以存取该对象。
1.引用的定义格式
        <类型说明符>  & <引用名> = <对象名>
例如:   int a;
         int &ta=a;
2  引用的主要用途是用作函数参数和函数的返回值。

以下两种情况可用:

#include <iostream>
#include <algorithm>
using namespace std;
void swap2(int*,int*);

int main()
{
	int a=4,b=3;
	swap2(&a,&b);
	cout<<a<<' '<<b<<endl; 
}

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

#include <iostream>
#include <algorithm>
using namespace std;
void swap2(int&,int&);

int main()
{
	int a=4,b=3;
	swap2(a,b);
	cout<<a<<' '<<b<<endl; 
}

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