C++:指针的用法以及一些其他内容

#include <iostream>
#include <Windows.h>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
	//指针
	double num = 1024.5;
	double* ptr_num = &num;
	void* ptr_num1 = &num;
	double* n_p = nullptr;
	cout << "num的值:" << num<<endl;
	cout << "num的地址:" << &num<<endl;
	cout << "ptr_num的值:" << ptr_num << endl;
	cout << "ptr_num的地址值:" << *ptr_num << endl;
	cout << "void型指针ptr_num1是否等于double型指针ptr_num:" << (ptr_num1 == ptr_num) << endl;
	cout << "n_p空指针的值:" << n_p << endl;
	//引用
	double&ref_num = num;
	cout << "ref_num引用num的值,是num的别名。:" << ref_num <<'\t'<<&ref_num<< endl;		//引用:相当于指针,但是比指针高效

	//指针数组
	double score[] = { 11,22,33,44,55 };
	double *ptr_score = score;//double *ptr_score = &score[0]
	cout << "指向数组的指针:" << ptr_score[2] << '\t' << *score << '\t' << *(score+1) << endl;//score=score[0]=ptr_score[0]
	cout <<"当指针碰见sizeof时会被打回原形,地址只占四了字节:"<< sizeof(score) << '\t' << sizeof(ptr_score) << endl;

	//容器:头文件#include<vector>
	vector<int>vect_num = { 10,20,80,5,66,30 };    //容器替代数组
	vect_num.push_back(100);					   //在vect_num容器尾部插入一个数字
	for (int i = 0; i < vect_num.size(); i++)	   //遍历“数组”,vect_num.size -返回容器中元素个数
	{
		cout << vect_num[i] << '\t';
	}
	cout << endl;

	//迭代器 iterator
	vector<int>::iterator it;							   //得到迭代器对象-实际上是一个指针对象 可以简写为:auto it;
	for (it = vect_num.begin(); it != vect_num.end(); ++it)//从第一个元素开始迭代,begin()、end()-返回容器首位元素的迭代器
	{
		cout << *it << '\t';
	}
	cout << endl;

	//排序,头文件#include <algorithm>
	sort(vect_num.begin(), vect_num.end());//正序
	for (it = vect_num.begin(); it != vect_num.end(); ++it)	//从第一个元素开始迭代
	{
		cout << *it << '\t';
	}
	cout << endl;
	reverse(vect_num.begin(), vect_num.end());				//逆序
	for (it = vect_num.begin(); it != vect_num.end(); ++it)	//从第一个元素开始迭代
	{
		cout << *it << '\t';
	}
	cout << endl;
	
	//动态分配内存
	int *ptr_int = new int;			//此时只能用指针访问这个值,当运行到这条语句时,才分配空间给他
	delete ptr_int;					//释放由new分配的内存
	int*intArray = new int[10];		//动态分配数组内存
	delete[]intArray;				//释放数组内存
	int(*ptr)[3] = new int[5][3];	//定义二维数组,降维操作。
	delete[]ptr;

	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值