1.c++冒泡排序的实现
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int array[10];
for (int i = 0; i < 10; i++)
{
array[i] = rand() % 50 + 1;
}
for (int i = 0; i < 10; i++)
{
cout << array[i] << " ";
}
cout << endl;
for (int i = 0; i < 10 - 1; i++)
{
for (int j = 0; j < 10 - 1 - i; j++)
{
if (array[j] > array[j + 1])
{
int temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
}
for (int i = 0; i < 10; i++)
{
cout << array[i] << " ";
}
return 0;
}
2.c++中字符串数组的应用
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name[3] = { "张三","李四","王五" };
for (int i = 0; i < 3; i++)
{
cout << name[i] << endl;
}
return 0;
}
呜呜呜,c++还能直接创建字符串数组太喜欢了,c语言根本没法这样做。
3.c++函数的分文件编写
1.创建.h后缀名的头文件
创建就行
2.创建.cpp后缀名的源文件
创建就行
3.在头文件中写函数的声明
#pragma once
#include <iostream>
using namespace std;
void swap(int a, int b);
4.在源文件中写函数的定义
#include "swap.h"//利用这个和头文件关联起来
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
}
5.在写项目的文件中应用
#include "swap.h"//包含那个自己创建的头文件," "代表自己写的
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
swap(a, b);//直接传
return 0;
}
4.c++指针
1.const修饰指针 ————常量指针
1.不能对指针指向的值做修改
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
const int* p = &a;
*p = 10;//错误的,vs直接报红,我们不能这样做
return 0;
}
2.能改变指针的指向
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
const int* p = &a;
p = &b;//这样我们是允许的
return 0;
}
2.const修饰常量 ————指针常量
1.能对指针指向的值做修改
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
int* const p = &a;
*p = 20;//可以这样做
return 0;
}
2.不能对指针指向做修改
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
int* const p = &a;
p = &b;//这样是错误的
return 0;
}
3.const既修饰指针,又修饰常量
1.指针指向的值不能修改
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
const int* const p = &a;
*p = 10;//这样不对
return 0;
}
2.指针指向的地址不能修改
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
const int* const p = &a;
p = &b;//我们也不允许这样操作
return 0;
}
5.c++结构体
1.结构体的定义和使用
在c++中,定义结构体时要struct关键字,但当使用它时,可以不带上关键字,这点比c语言方便多了
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct Student {
string name;
int age;
double score;
};
int main()
{
Student s1;//我们可以直接用名字在c++中
s1.name = "张三";
s1.age = 20;
s1.score = 100;
cout << "姓名:" << s1.name << "年龄:" << s1.age << "成绩:" << fixed << setprecision(2) << s1.score << endl;
return 0;
}
6.在c++中还可以这样使用字符串
#include <iostream>
#include <string>
using namespace std;
struct Teacher {
int data;
string name;
};
int main()
{
Teacher teacher[3];
string fuzhi = "ABC";//像一个字符数组一样
for (int i = 0; i <3; i++)
{
teacher[i].data = i;
teacher[i].name = "teacher_";
teacher[i].name += fuzhi[i];//竟然可以直接加上
}
for (int i = 0; i < 3; i++)
{
cout << teacher[i].data <<" ";
cout << teacher[i].name << endl;
}
}