Day 8
指针上
1.用法
int *p;
p=&a;
2.
c++中swap函数接收的是值
3.指针的引用
void swap(int *&p1,int *&p2){//指针的引用}
4.sort(p, p + t, greater<int>()); 降序排序
5.求和函数
#include<numeric>//求和头文件
double solve(double *p,int t){
sort(p,p+t);
double aver=accumulate(p,p+t,0);//初始值
return aver/t;
}/*introsort内省排序
(快速排序(Quicksort)、
堆排序(Heapsort)[二叉树]、
插入排序(Insertion sort))*/
6.a.data()
7.
/*unsigned int Mystrlen(const char *p){//unsighed 无负数
if (p == nullptr) return 0;//防止空指针
int sum(0);
while(*p!='\0')const char{//const char 依赖'\0'
sum++;
p++;
}
return sum;
}
int main(){
string a;
getline(cin,a);//一般用于字符串输入,c++风格
cout<<Mystrlen(a.c_str());//c风格转换
return 0;
}*/
8.vector引用及转换
unsigned Mystrlen (const vector<char>& vec){
return vec.size();
}
vector<char>b(a.begin(),a.end());//转换
9. getline(cin,a);//头文件string
/* cin.getline()(C 风格,处理char[])
char buf[10];
cin.getline(buf, 10);同样易读取残留'\n'
在cin >> x后,用cin.ignore()忽略缓冲区的'\n'
10.strlen函数
strlen函数(返回 size_t(无符号整数) 类型)c风格
size_t len = (str == nullptr) ? 0 : strlen(str);防空
#include<cstring> // 必须包含头文件
int main() {
// 示例1:字面量字符串
const char* str1 = "Hello";
cout << "str1长度:" << strlen(str1) << endl; // 输出 5(H e l l o → 无\0)
// 示例2:字符数组(带结束符)
char str2[] = {'w', 'o', 'r', 'l', 'd', '\0'};
cout << "str2长度:" << strlen(str2) << endl; // 输出 5
// 示例3:字符数组(无结束符,危险!)
char str3[] = {'a', 'b', 'c'}; // 无'\0',属于“非法C风格字符串”
cout << "str3长度:" << strlen(str3) << endl; // 未定义行为(随机值)
return 0;
}
特性 strlen sizeof
本质 函数,计算有效字符数 运算符,计算内存占用字节数
是否包含 '\0' 不包含 包含(若字符串在数组中)
适用对象 仅 C 风格字符串(char*/char[]) 任意数据类型(数组、基本类型等)
计算时机 运行时(遍历内存) 编译时(静态计算)
11.指针不能加法
12.冒泡排序
void bubbleSort(int *p,int c){
for(int i=0;i<c-1;i++){
bool swapped=false;
for(int j=0;j<c-1-i;j++){
if(*(p+j)>*(p+j+1)){
swap(*(p+j),*(p+j+1));
swapped=true;
}
}
if(!swapped)break;
}
}
13.交换
#include<iostream>
using namespace std;
void swap(int *a,int *b){
int tem;
tem=*a;
*a=*b;//换值不换地址,你换的地址无效
*b=tem;
}
14.指针数组
#include<iostream>
using namespace std;
int a[3][3]={1,2,3,4,5,6,7,8,9};
int *pa[3]={a[0],a[1],a[2]};//147
void print(int *p){
cout<<*p<<','<<*(p+1)<<','<<*(p+2)<<endl;//输出123,456,789
}
int main(){
int i;
for(i=0;i<3;i++){
print(pa[i]);
}
return 0;
}
