【牛客题霸】语法篇 - C++入门72题

数字和基本语法

一些笔记:cin

注意,用户在输入数字时要用空格分隔数字。 这样 cin 才能知道每个数字的开始和结束位置。 在每个数字之间输入多少空格并不重要,需要注意的是,在最后一个数字输入之后,必须按回车键。

cpp2. double小数转int整数,四舍五入

double a;
int b = a;
会直接输出a的整数部分。
考点:负数;小数点后没有数字

方法一:round函数

四舍五入到最邻近的整数
需要额外 #include<math.h>

#include<math.h>
round(1.56)=2.000000
round(-1.99)=-2.000000

方法二:直接写

double x;
int y;
if(d>=0) y = d+0.5;
    else y = d- 0.5;
cout << y <<endl;

cpp7. 三元表达式

#include <iostream>
using namespace std;

int main() {
    
    int a, b, c;
    cin >> a;
    cin >> b;
    cin >> c;

    // write your code here......
    (a>=b&&a>=c? (cout<<a):(b>=a&&b>=c? cout<<b : cout<<c));
    cout<<endl;

    return 0;
}

cpp8. 取小数点后1位

setprecision()为了精确小数位数
setiosflags(ios::fixed)为了保证当只有一位小数位且该小数位是0时,避免用e的指数输出

cout << setiosflags(ios::fixed) << setprecision(1) << cost << endl;

取小数点后1位 :

printf("%.2lf\n",sum);

输出两个数,中间隔空格:

cout<<fixed<<setprecision(1)<< AA <<" "<<setprecision(1)<< BB <<endl;

cpp10-11. switch

题目:
判断成绩等级(不要忘记在 case 语句的结尾添加 break 语句)
判断季节(闭区间:** … 左右必须加空格**)
default可以处理12、1、2这样不好分类的case,但可能与switch之前的不合法判断重复!因此,不合法判断写作if,switch写在else中较好!或者如下,提前return:

    cin >> score;
    if(score > 12 || score < 0){
        cout<<"不合法"<<endl;
        return 0;
    }
    switch(score / 10){ 
            case 10: case 9:                        //可以一起取两种情况
                cout << "优秀" << endl; break;
            case 3 ... 5:                           //连续的值
                cout << "春季" << endl;  break;
            default:                                //其余情况
                cout << "差" << endl;

cpp12.for循环の跳步:

for(int i = n; i >0; i-=2)

cpp14.水仙花数:获取个十百位数字的方法 + main以外的bool函数

#include <iostream>
using namespace std;
bool isNarcissus(int num){
 //   bool flag;//不需要flag,直接return即可!
 //   int a = num/100;//百位
 //   int b = (num%100)/10;//十位
 //以下是另一种方法,更通用but需要先用tmp保存初始num值
    int tmp = num;
    int c = num%10;//个位
    num /= 10;
    int b = num % 10; //十位
    num /= 10;
    int a = num % 10; //百位
    if ((a*a*a + b*b*b + c*c*c)==tmp){
       // flag= true;
        return true;
    }else  return false;//flag = false;
   // return flag;
}
int main(){
    for(int i = 100; i <=999; i++){
        if (isNarcissus(i)) cout<<i<<endl;
    }
    return 0;
}

cpp16. long long的应用

求9 + 99 + … + 9999999999(10个9) 的和
如果用int会溢出。

#include <iostream>
using namespace std;
int main(){
    long long  sum = 0;
    long long  j = 0;
    for(int i = 0; i<10; i++){
        j = j*10 + 9;
        sum += j;
}
    cout<<sum<<endl;
    return 0;
}

cpp17 如何输出“100.0 50.0”

cout<<fixed<<setprecision(1)<< sum <<" "<<setprecision(1)<< x/2 <<endl;

double一般就用来表示小数;
cin 可以连续从键盘读取想要的数据,以空格、tab 或换行作为分隔符,所以输入100 3就等同于输入了100、输入了3(空格分隔)
https://blog.csdn.net/Buster001/article/details/100083803后续去看!

数组

cpp19. 获取数组最大最小值

自己思路:预定max为整数下限INT_MIN,min为整数上限INT_MAX
实际上可以将其都预定为 arr[0],这样输出的总为数组中的实际值;
int数组初始化为空:int arr[6] = {};初始化为0:int arr[6] = { 0 }

#include <iostream>
using namespace std;
int main(){
    int arr[6] = {};
    int max = 0;
    int min = 99999;
    for(int i = 0; i < 6; i++){
        cin>>arr[i];
        if(arr[i] > max) max = arr[i];
        if(arr[i] < min) min = arr[i];
    }
    cout<<min<<" "<<max<<endl;
    return 0;
}

int数组创建+输入+求元素个数

    int arr[6] = { 0 };
    int len = sizeof(arr) / sizeof(int);   // 24/4=6
    
    for (int i = 0; i < len; i++) {
        cin >> arr[i];
    }

另外:
char 数组里面是一个1 个元素1 个字节
int 和 long 数组里面在32位环境中都是1 个元素 4 个字节
long long 数组里面是1 个元素 8个字节:

#include<iostream>
using namespace std;
int main()
{
	char arr1[10];        // 10
	int arr2[10];        // 40
	long arr3[10];        // 40
	long long arr4[10];   // 80
	cout << sizeof(arr1) << endl << sizeof(arr2) << endl << sizeof(arr3)<<endl<<sizeof(arr4);
	return 0;
}

cpp21.冒泡排序

在这里插入图片描述
输入一个6元素的数组,进行冒泡排序
(未知个数,则使用:

	int arr[9999] = { 0 };
	int len = sizeof(arr) / sizeof(int);
	for (int i = 0; i < len; i++) { ...

重点在于 for(int i = 0; i <5 ; i++) (01234)和 for( int j = 0; j<5-i; j++)(01234,0123,012,01,0)的含义和上限:
i 表示遍历的轮数,总共需要len-1轮;实际上只是用来计数的,用12345、54321也一样,不参与实际操作(swap)
j 表示每次遍历相邻的j和j+1两个元素
i 和 j 的关系是和为 len-1,因为第一轮需要遍历到倒数第二和第一个元素,最后一轮只比较第一二个元素。

另外,标准库也可以使用swap(arr[j], arr[j + 1]) !

#include<iostream>
using namespace std;
int main(){
    int arr[6]= {0};
    for(int i = 0; i<6;i++){
        cin>>arr[i];
    }
    for(int i = 0; i <5 ; i++){
        for( int j = 0; j<5-i; j++){
            if(arr[j]>arr[j+1]){
                int tmp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1]= tmp;
            }
        }
    }
    for(int i = 0; i<6;i++){
        cout<<arr[i]<<" ";
    }
    cout<<endl;
    return 0;
}

复杂度分析:
时间复杂度:O(n2),n为数组长度,冒泡排序两层循环,最坏情况下是逆序,一共比较(n∗(n−1)/2)次
空间复杂度:O(1),无额外空间

cpp22.选择排序

在这里插入图片描述
以下的注释行,死记住……不能改任何一处

#include <iostream>
using namespace std;

int main() {
    int arr[6] = {0};
    int len = sizeof(arr) / sizeof(int);
    for(int i = 0; i < len; i++) cin>>arr[i];
    
    for(int i = 0; i <len-1 ; i++){
        int min = i;/
        for(int j = i+1; j < len; j++){
            if(arr[j] < arr[min]) min = j;/
        }
        swap(arr[i], arr[min]);/交换两个变量的内容
    }
    
    for(int i = 0; i < len; i++) cout<<arr[i]<<" ";
    cout<<endl;
    return 0;
}

复杂度分析:
时间复杂度:O(n2),一共n轮选择,每轮要比较O(n)次
空间复杂度:O(1),无额外空间

cpp23. 创建二维int数组

    int arr[4][3] = {
        22,66,44,        //有逗号,然后换行即可
        77,33,88,
        25,45,65,
        11,66,99         //没有逗号
    };

cpp29. 创建动态数组(※再看)

为什么网上都说要用 arr = (int*)malloc( arrLen*sizeof(int) );

int* arr = new int[n];

解析用的是

int* arr = new int[n];

之后一切如常。。。

#include <iostream>
using namespace std;
int main() {

	int n;
	cin >> n;
	int* arr = new int[n]; //指针申请n个空间
    for(int i = 0; i < n; i++) //初始化
        arr[i] = n + i;
    for(int i = 0; i < n; i++) //输出
        cout << arr[i] << " ";
	return 0;
}

cpp26. 指针遍历 int 数组+输出

类似指路:cpp28指针处理char数组+输出
#include<iostream>
using namespace std;
int main(){
    int arr[6] = {0};
    int len = sizeof(arr)/sizeof(int);
    for(int i = 0; i <  len ; i++)  cin>>arr[i];

    int* p =  arr;
    while(*p != '\0'){///for (ptr ; ptr < arr + len ; ptr++)
        cout<< *p <<" ";
        p++;
    }
    cout<<endl;
    return 0;
}

创建二维数组

没用过,直接创建在牛客里好像也不是不行。。。下面的用法看看

    cin>>n;
    int** a = new int*[n];
    for (int i = 0; i < n; i++) {
        a[i] = new int[n];
        for (int j = 0; j < n; j++) {
            ...

cpp30.数组元素处理

语法要点:
void func(int* p, int n) int p1[n] = {0};会报错!
i++是先用i的值,语句执行完,i再++

主要思路:

双指针

自己的思路:

#include <iostream>
using namespace std;

void func(int* p, int n);

int main() {

    int arr[6] = { 0 };
    for (int i = 0; i < 6; i++) {
        cin >> arr[i];
    }

    func(arr, 6);

    for (int i = 0; i < 6; i++) {
        if (i == 5) {
            cout << arr[i] << endl;
        }
        else {
            cout << arr[i] << " ";
        }
    }

    return 0;
}
void func(int* p, int n) {
    // write your code here......
    ///int p1[n] = {0};会报错!
    int count = 0;
    for (int i = 0, j = 0; i<n; i++){ 
        if (p[i] != 0 ){
            //p1[j] = p[i];
            p[j] = p[i];
            j++;
        }else count++;
    }
    while(count != 0) {//exp: count = 1, n = 6 ,p[5] = 0
        p[n-count] = 0;
        count--;
    }
}

答案的思路:
在这里插入图片描述

void func(int* p, int n) {

    //id指向第一个0所在位置
    int id=0;
    //i指向游标所在位置,遍历数组所有元素
    for(int i=0;i<n;i++){
        if(p[i]!=0){
            int temp=p[i];
            p[i]=p[id];
            p[id++]=temp;
        }
    }
}

cpp61. 数组类的构造函数

又是一道没用过只能先粘贴过来的题。。。

#include<bits/stdc++.h>
using namespace std;
class Array{
	private:
		int n;//数组大小 
		int *a;//数组 
	public:
		// write your code here.....
       Array(){
           cin>>n;
           a = new int[n];
           for(int i = 0;i<n;i++)cin>>a[i];
       }
    
        
		~Array(){
			delete []a;
		}
		void show(){
			for (int i=0;i<n;i++) cout<<a[i]<<' ';
		}
};
int main(){
	Array a;
	a.show();
	return 0;
}

cpp72. 找到数组里的第k大数(C++)

vector的初始化和加入值
	vector<int>a;
        a.push_back(num);

字符串

字符串介绍:
https://www.nowcoder.com/knowledge/intro-index?kcid=95

字符串是存储在内存连续字节中的一系列字符。C++ 处理字符串有两种方式,一种是 C-风格字符串,另一种是基于 string 类

C-风格字符串

可以将字符串存储在 char 数组中,每个字符都位于自己的数组元素中。

char name[5] = {'K', 'i', 't', 't', 'y'};         // 字符数组,不是字符串

C-风格字符串是以空字符结尾(空字符被写作\0,ASCII码为0),用来标记字符串的结尾。

char name[6] = {'K', 'i', 't', 't', 'y', '\0'};  // C-风格字符串

字符数组初始化为字符串,可以使用双引号(“”)将字符串内容括起来。

char name[16] = "Hello Kitty";
char name[] = "Daniel";
// 双引号括起来的部分称之为字符串常量或者字符串字面值

string 类

可以使用 string 类型的变量来存储字符串。提供了将字符串作为一种数据类型的表示方法,使用起来比数组简单。
要使用 string 类,必须包含头文件**#include< string >**
string 初始化

string str = {'h', 'e', 'l', 'l', 'o'};
string str = "hello world";
string str = {"hello world"}
string str {"hello world"}
显著区别:

① 可以将一个 string 对象赋值给另一个 string 对象,而数组不可以。

string str1;
string str2 = "hello";
str1 = str2;

② 可以使用运算符 + 将两个 string 对象合并起来,还可以使用 += 运算符。

string str3 = str1 + str2;
str1 += str2;

③ string对象用size()和length()方法获取字符串长度。

cpp24.string输入+合并+输出

输出两个字符串拼接后的结果
输入:
hello
nihao
复制
输出:
hellonihao

#include <iostream>
#include <string>        ///!
using namespace std;
int main() {
        
    string s1, s2;
    getline(cin, s1);
    getline(cin, s2);
 
    s1 = s1+s2;
    cout<<s1<<endl;

    return 0;
}

cpp56.string输入+统计其中某些char的个数

题目描述:输入一个只包含’a’,‘b’,‘c’的字符串,问’a’,‘b’,'c’分别出现了多少次。

getline(cin, s) 可以包含空格,可以输入ab c这样的字符串。
sizeof(s) / sizeof(string) 值为1,不能这样获取字符串长度,应该用s.size()或者s.length()。
s[i] 是单引号的 ‘a’

#include<bits/stdc++.h>
using namespace std;
int main(){
    string s;
    getline(cin, s);
    // write your code here......
   // int len = sizeof(s) / sizeof(string);cout<<len<<endl;//len = 1
    int aa = 0, bb=0, cc=0;
    for(int i = 0; i<s.size(); i++){
        if(s[i]=='a')aa++;
        else if(s[i]=='b')bb++;
        else if(s[i]=='c')cc++;
    }
    cout<<aa<<" "<<bb<<" "<<cc<<" "<<endl;
    return 0;
}

cpp34(类似) 统计空格、数字、字母等

#include <iostream>
#include <string>

using namespace std;

int main() {

	string str;
	getline(cin, str);

	int whitespace = 0;
	int digits = 0;
	int chars = 0;
	int others = 0;

	// write your code here......
    for(int i = 0; i < str.length(); i++){ //遍历字符串
        if(isalpha(str[i])) //判断是否是字母
           chars++;
        else if(isdigit(str[i])) //判断是否是数字
           digits++; 
        else if(isspace(str[i])) //判断是否是空格
           whitespace++;
        else
           others++;
    }
    
	cout << "chars : " << chars
		<< " whitespace : " << whitespace
		<< " digits : " << digits
		<< " others : " << others << endl;

	return 0;

}

cpp27. char ch[100] :初始化、输入、输出;指针法求长度

初始化:char ch [100] = { 0 };
输入:cin . getline ( str , sizeof ( ch ) ); 包含空格
输出:cout << str << endl; 直接输出

思路:
求长度,便捷是用 char 数组,而不是string;
但此时对char 数组,不可以用 int len = sizeof(ch) / sizeof(char),会直达9999(数组的真正长度)
正解如下:(指针法)

#include <iostream>
#include <string>
using namespace std;

int main() {
    char ch[9999] = {0};
    cin.getline(ch,sizeof(ch));
    //int len = sizeof(ch) / sizeof(char);///不可以用这句,会直达9999(数组的真正长度)
    char* p = ch;
    int i = 0;
    while(*p != '\0'){
        i++;
        p++;
    }

    cout<<i<<endl;
    return 0;
}

cpp28. 指针法,创建新 char 数组+输出

题目描述:

在 char ch[100] 原字符串后半段,创建新字符串:指针做法

判断字符数组结束的标志:

for(int i = 0; ch [ i ] ! = ’ \ 0 ’ ; i++)
或者
while (*p != ‘\0’) ,注意是反斜杠0
或者
for (ptr ; ptr < arr + len ; ptr++)

求字符数组长度:

与 int 数组类似,可用 int len = sizeof (ch) / sizeof (char)

指针:

char* p = ch 指向 char数组的起始处,+ m - 1 指向第 m 个元素;
*p 表示 p 所指向的值

#include <iostream>
#include <string>
using namespace std;
int main(){
    char ch[30]={0};
    char copych[30]={0};
    cin.getline(ch, sizeof(ch));/
    int m;
    cin>>m;
    char* p = ch + m - 1;//
    char* q = copych;
    for(int i = 0; ch[i]!='\0'; i++){///while(*p != '\0')    //判断字符数组结束的标志
        *q = *p;/复制值
        q++;/同时移动
        p++;
    }
    cout<<copych<<endl;
}

不用指针的做法:

...
#include <string>//上面的char数组做法,不需要额外这句
int main(){
    string s;
    getline(cin,s);
    int len = s.size();
    int m;
    cin>>m;
    string s1="";
    for(int i = m-1; i < len; i++){
        s1+=s[i];
    }
    cout<<s1<<endl;
    return 0;
}

cpp29.char s[100]输入+转化为string+统计子串出现次数-find函数

用find函数
#include <iostream>
#include <cstring>
using namespace std;

int main() {

    char str[100] = { 0 };
    char substr[100] = { 0 };

    cin.getline(str, sizeof(str));
    cin.getline(substr, sizeof(substr));

    int count = 0;

    //转化为字符串!!!!!!!!!!!!!!
    string str1(str);
    string str2(substr);
    
    int i=0;
    //从str1下标i开始查找str2
    while(str1.find(str2,i)!=-1){
        //如果找得到,计数加1
        count++;
        //i从找到的位置,后移一位
        i=str1.find(str2,i)+1;
    }

    cout << count << endl;

    return 0;
}
不用find函数:(用char s[100])
#include <iostream>
#include <cstring>
using namespace std;

int main() {
   
	char str[100] = { 0 };
	char substr[100] = { 0 };

	cin.getline(str, sizeof(str));
	cin.getline(substr, sizeof(substr));

	int count = 0;
    for(int i = 0; str[i] != '\0'; i++){ //遍历字符串str
        bool flag = true; 
        for(int j = 0; substr[j] != '\0'; j++){ //以字符串str的i位置为起点,每次同步遍历substr长度
            if(str[i + j] != '\0' && str[i + j] == substr[j]) //比较每个字符
                continue;
            else{
                flag = false; //不相同,这一次不是子串
                break;
            }
        }
        if(flag)
            count++;
    }
	cout << count << endl;

	return 0;
}

cpp31. 比较字符串大小:mian以外的函数

比较思路:不等长则长的大;等长则有第一次出现更大字符的大
例如: hello < helloworld hello < Hello

注意点:
函数顺序:先声明,再main函数,再定义
(const char* src, const char* dst)在函数体内直接用,不可以另外初始化
求char数组长度的便捷方法: int len1=strlen(src);

    int len1=strlen(src);
    int len2=strlen(dst);
    int i=0,j=0;
    while(i<len1&&j<len2){
        //如果src当前字符小于dst,说明src小于dst,返回-1
        if(src[i]<dst[j])  return -1;
       ...

自己的做法:

#include <iostream>
using namespace std;
//先声明,再main函数,再定义
int mystrcmp(const char* src, const char* dst);
int IfLenEqual(const char* src, const char* dst);

    
int main() {

    char s1[100] = { 0 };
    char s2[100] = { 0 };

    cin.getline(s1, sizeof(s1));
    cin.getline(s2, sizeof(s2));

    int ret = mystrcmp(s1, s2);

    cout << ret << endl;

    return 0;
}
int mystrcmp(const char* src, const char* dst) {
    int equal = IfLenEqual(src,dst);
    if(equal == 1) return 1;
    if(equal == -1) return -1;
    if(equal == 0){
        while(*src!='\0' && *dst !='\0'){
            if(*src > *dst)return 1;
            if(*src < *dst)return -1;
            src++;
            dst++;
        }
        return 0;
        
    }
    return 0;
}
int IfLenEqual(const char* src, const char* dst) {
    int len1 = 0, len2= 0;
    //char* p = src;///不可以另外初始化
   // char* q= dst;
    while(*src != '\0') {
        len1++;
        src++;
    }
    while(*dst != '\0') {
        len2++;
        dst++;
    }
    return len1>len2 ? 1 : len1<len2 ? -1 : 0;
}

cpp33. 统计子串出现次数:char转str + 使用find函数

char转str :string str1 ( ch1 );
注意 i是起始位置不是找到位置,所以这样可能会错过或者重复找到目标str

#include <iostream>
#include <cstring>
using namespace std;

int main() {

    char str[100] = { 0 };
    char substr[100] = { 0 };

    cin.getline(str, sizeof(str));
    cin.getline(substr, sizeof(substr));

    int count = 0;

    // write your code here......
    string str1(str);
    string str2(substr);
    int i = 0;
    while(str1.find(str2,i) != -1){///while找到了(第一次必然找到,否则题目不成立)
        /*i += strlen(substr);//no/(注意 i是起始位置不是找到位置,所以这样可能会错过或者重复找到目标str)
        cout<<"stri:"<<str[i]<<"  ";*/
        i = str1.find(str2 , i) +1;///从找到的下一位开始 
        count ++;
    }

    cout << count << endl;

    return 0;
}

cpp34. 统计字符串中各种字符出现次数

string比char数组好用:不用初始化,输入语句短,长度可以直接用length()不用用’\0’判断

#include <iostream>
#include <string>
using namespace std;
int main(){
    int chars = 0, whitespace = 0, digits = 0, others = 0;
    string ch;//[999] = {0};
    //cin.getline(ch , sizeof(ch));
    getline(cin , ch);
    //int len = sizeof(ch) / sizeof(char);
    int len = ch.size();
    for(int i = 0; i < len ; i++){
        if(isalpha(ch[i])){
           chars++;
        }
        else if(isdigit(ch[i])){
            digits++;
        }   
        else if(isspace(ch[i])){
            whitespace++;
        }            
 
        else others++;
           
    }
    cout<<"chars : "<<chars<<" whitespace : "<<whitespace
        <<" digits : "<<digits<<" others : "<<others<<endl;
    return 0;
}

cpp58. 编写【函数】实现字符串翻转(引用方式)

相当于写一个swap函数,其中函数参数用到了引用&
注意两点: length() /2 以及 length()-1 再-i

#include<bits/stdc++.h>
using namespace std;
// write your code here......
void swap( string& s){
    for(int i = 0; i < s.length()/2; i++){
        char ch = s[i];
        s[i] = s[s.length()-i -1 ];
        s[s.length()-i - 1] = ch;
    }
}

int main(){
    string s;
    getline(cin,s);
    // write your code here......
    swap(s);
    cout<<s<<endl;
    return 0;
}

cpp49. 用set去除字符串中重复的字符

set

是STL的集合容器,相同的元素在set中只保留一次,而且set还会依赖于红黑树自动排序,如果是字符依靠ASCⅡ码的大小排序。
①引入set,需要#include <set>
②创建一个 set :set<char> sett; 注意只有一个参数
③在 set 中给元素赋值:不能直接用 = 赋值,而是要插入元素:sett.insert(str[i]);
遍历 set 中每个元素的内容

    for(auto iter = sett.begin(); iter!= sett.end(); iter++){///set<char>iterator iter
        cout<<*iter;
    }

复杂度分析:
时间复杂度:O(nlog2n),其中n为字符串长度,一共n个字符,每次插入的代价都是O(log2n)
空间复杂度:O(n),集合的大小最坏为n

#include <iostream>
#include <set>// write your code here......
using namespace std;

int main() {

    char str[100] = { 0 };
    cin.getline(str, sizeof(str));
    // write your code here......
    set<char> sett;
    for(int i = 0; str[i]!= '\0'; i++){
        sett.insert(str[i]);
    }
    for(auto iter = sett.begin(); iter!= sett.end(); iter++){///set<char>iterator iter
        cout<<*iter;
    }
    cout<<endl;

    return 0;
}

cpp70. 查找 - set :reverse_iterator 容器倒序遍历-upper_bound(x)-berak

使用容器: set
解法一:upper_bound(x)-berak

#include<bits/stdc++.h>
using namespace std;
int main(){
	set<int>s;
	//write your code here......
	int n,m,x,a;
    cin>>n>>m;
    for(int i=0;i<n;i++)
    {
        cin>>a;
        s.insert(a);//有序存储不重复
    }
    while(m--)
    {
        cin>>x;
        auto it=s.upper_bound(x);//返回第一个大于x的元素对应的迭代器指针
        if(it==s.end()) cout<<-1<<endl;
        else  cout<<*it<<endl;
    }
	return 0;
}

解法二:输入数量过多时会报错运行超时

#include<bits/stdc++.h>
using namespace std;
int main(){
	set<int>sett;
	//write your code here......
	int n, m;
    cin>>n>>m;
    vector<int> a;
    for(int i = 0; i < n; i++){
        int ax;
        cin>>ax;/space
       // a.push_back(ax);
        sett.insert(ax);
    }
    //for(auto it = sett.begin();it!=sett.end();it++)cout<<*it;///3 5 6 8 
    while(m){
        m--;
        int x;
        cin>>x;
        bool f = 0;
        for(set<int>::iterator iter = sett.begin(); iter != sett.end();iter++){/// NO <=
        //for(vector<int>::iterator iter=a.end()-1;iter!=a.begin();iter--){
        //for(set<int>::reverse_iterator iter = sett.rbegin(); iter != sett.rend();++iter){
            if(*iter > x){// && *(iter+1) >= x
                //cout<<"x: "<<x<<"  iter: "<< *iter <<endl;
                cout<< *iter <<endl;
                f = 1;
                break;
            }
            //continue;  
        }
        if(f == 0) cout<<-1<<endl; ///不需要“-1”
    }
	return 0;
}

cpp50. 统计字符串中各字母字符对应的个数-map

map

map 提供的是一种键值对容器,里面的数据都是成对出现的:第一个值称之为关键字(key),只能在 map 中出现一次;第二个称之为该关键字的对应值(value)。
① 引入map,需要#include <map>
②创建一个 map :map<char, int> mapp; 注意有两个参数,并注意顺序(本题计数题,后一个是int用来计数)
③在 map 中给元素赋值:可以直接用等号赋值,但要注意顺序mapp [ str [ i ] ] = 5
遍历 set 中每个元素的内容:与 set 类似,但有两个子树,用 iter -> 指向:

    for(auto it = mapp.begin(); it != mapp.end(); it++){
        cout<< it->first <<':'<< it->second <<endl;
    }
#include <iostream>
// write your code here......
#include <map>
using namespace std;

int main() {

    char str[100] = { 0 };
    cin.getline(str, sizeof(str));

    // write your code here......
    map<char, int> mapp;
    for(int i = 0; str[i]!='\0'; i++){
        if(isalpha(str[i]))    mapp[str[i]]++;
    }
    for(auto it = mapp.begin(); it != mapp.end(); it++){
        cout<< it->first <<':'<< it->second <<endl;
    }

    return 0;
}

cpp71. 查找 - map

#include<bits/stdc++.h>
#include<map>
using namespace std;
int main(){
	//write your code here......
	map<int,string>ma;
    int n,m,x;
    cin>>n>>m;
    while(n--)
    {
        cin>>x;
        ma.insert(pair<int ,string>(x,"yes"));
    }
    while(m--)
    {
        cin>>x;
        auto it=ma.find(x);
        if(it==ma.end()){cout<<"no"<<endl;}
        else{
            cout<<"yes"<<endl;
        }
    }
	return 0;
}

自己写的,居然也行

#include<bits/stdc++.h>
using namespace std;
int main(){
	//write your code here......
	int n,m;
    cin>>n>>m;
    map<int, string> mapp;
    for(int i = 0; i<n;i++){
        int x;
        cin>>x;
        mapp[x]="yes";
    }
    while(m--){
        int y;
        cin>>y;
        if(mapp[y]=="yes")cout<<"yes"<<endl;
        else cout<<"no"<<endl;
    }
	return 0;
}

cpp55. 十进制 int 转十六进制 string

reverse / swap / char / string 插入 + 转int

使用 swap 需要#include <algorithm>,reverse不用
s = snum + s;这样就可以把字符 snum 加在字符串 s 前面!!!就不用后续的reverse了!!!
swap 和 reverse 的共同用法:swap(s.begin(), s.end()); reverse(s.begin(), s.end());
swap只交换两个元素,全部反转要用reverse!!!

十进制转其他进制的原理:
在111图片描述注意循环的开头判断是% 处理是/

while(n%16 != 0){
        ...
     n = n/16;
     }

整体代码如下:

#include <iostream>
#include <string>
//#include <algorithm> // Needed for swap
using namespace std;

string toHexString(int n);

int main() {

    int n;
    cin >> n;

    string hexStr = toHexString(n);
    cout << hexStr << endl;

    return 0;
}

string toHexString(int n) {
    // write your code here......
    string s = "";
    char snum;
    while(n%16 != 0){
        int num = n % 16;
        if (num < 10)  {
            snum = num + '0';
            //cout<<"0-9 : "<<snum<<endl;
        }
        else {
            num -= 10;
            snum = 'A' +  num;
            //cout<<">=10 : "<<snum<<endl;
        }
        //s += snum;
        s = snum + s;/这样就可以把字符 snum 加在字符串 s 前面!!!就不用后续的reverse了!!!
        n = n/16;
    }
    //swap(s.begin(), s.end());不可以,swap只交换两个元素,全部反转要用reverse!!!
    ///reverse(s.begin(), s.end());
    return s;
   
}

面向对象

cpp32. 编写函数,实现swap功能:【指针】或【引用】形式

尤其注意参数 + 内部的表示 + main函数中的调用方式,二者不同!!
另外系统自带swap函数的,所以自己命名为swap即使写错了也不会报错!

#include <iostream>
using namespace std;

// write your code here......
void swap1(int *p, int *q);
void swap2(int &a, int &b);

int main() {

    int m, n;
    cin >> m;
    cin >> n;

    swap1(&m,&n); // 指针变量
    swap2(m,n);  //引用变量
    swap1(&m,&n); // 指针变量    

    cout << m << " " << n << endl;

    return 0;
}
void swap1(int *p, int *q)
{
    int temp = *p;
    *p = *q;
    *q = temp;
}
void swap2(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

cpp25. 设计【结构体struct】

结构体 struct 和 类 class 都在main外,最后有分号(函数不用分号)

#include <iostream>
#include <string>
using namespace std;

struct student{///要提出来,在main外面写
        string name;
        int age;
        double height;///要注意输入范例的height是小数
    };;

int main(){

    
    student st;
    /*string name1;
    getline(cin , name1);
    int age1;
    cin>>age1;
    int height1;
    cin>>height1;
    cout<< name1 <<" "<< age1<<" "<<height1<<endl;*/
    cin>>st.name >> st.age >> st.height;
    cout<<st.name<<" "<<st.age<<" "<<st.height<<endl;
    
    return 0;
}

cpp38-59-60. 设计【类class】

#include <iostream>
using namespace std;

class Cube {
    private:
    int length;
    int width;
    int height;
    public:
    //Cube(){}///构造函数---> Cube c;  也可以没有
    
    //int setLength(int length){ return length}; WRONG!
    ///function no " ; "!!!!!
    void setLength(int l){ length = l;}void ----> c.setLength(length);
    void setWidth(int w){ width = w;}w = width WRONG!!!!
    void setHeight(int h){ height = h;}
    
    int getLength(){return setLength(length)};  WRONG!
    int getLength(){return length;}///-----> void setLength
    int getWidth(){return width;}
    int getHeight(){return height;}
    
    
    int getArea(){ return 2*(length*width+length*height+width*height);}// 乘法不需要再()
    int getVolume(){ return getLength() * getWidth() * getHeight();}
    

};

int main() {

    int length, width, height;
    cin >> length;
    cin >> width;
    cin >> height;

    Cube c;
    c.setLength(length);
    c.setWidth(width);
    c.setHeight(height);

    cout << c.getLength() << " "
        << c.getWidth() << " "
        << c.getHeight() << " "
        << c.getArea() << " "
        << c.getVolume() << endl;

    return 0;
}

cpp39. 【类】套【类】的运用

题意:判断某点( x1, y1 ) 与圆心( x2 , y2 )半径 r 的圆的位置关系

#include <iostream>
#include <cmath>
using namespace std;

// 点类
class Pointer {

    private:
        int x;  // x 坐标
        int y;  // y 坐标

    public:
        void setX(int parameter_x) {
            this->x = parameter_x;搞清楚顺序:x 由 parameter_x 赋值
        }
        int getX()    return x;
       
        void setY(int parameter_y) {
            this->y = parameter_y;
        }
        int getY()   return y;
        }

};

// 圆类
class Circle {

    private:
        Pointer center; // 圆心
        int radius; // 半径

    public:
        void setCenter(int x, int y) {
            center.setX(x);///---->Pointer center
            center.setY(y);
        }

        void setRadius(int radius) {
            this->radius = radius;
        }

        // write your code here......
        void isPointerInCircle( Pointer pp){
            int xx = pp.getX() - center.getX(); |x1 - x2|
            int yy = pp.getY() - center.getY(); |y1 - y2|
            int rr = sqrt(xx*xx + yy*yy);不想include<cmath>就把r也平方了
            if(rr < radius) cout<<"in"<<endl;
            else if(rr == radius) cout<<"on"<<endl;
            else cout<<"out"<<endl;
            
        }
        

};

int main() {

    // 键盘输入点的坐标
    int x, y;
    cin >> x;
    cin >> y;

    // 创建一个点
    Pointer p;
    p.setX(x);
    p.setY(y);

    // 创建一个圆
    Circle c;
    c.setCenter(5, 0);
    c.setRadius(5);

    // 判断点和圆的关系
    c.isPointerInCircle(p);

    return 0;
}

cpp40. 构造函数

重点关注:
构造函数这样创建:

Person (string name1, int age1){//Person pp(string name1, int age1){
            this->name = name1;
            this->age = age1;
        }

构造函数这样调用:

    Person p(name, age);

全文:

#include <iostream>
#include <string>
using namespace std;

// Person类
class Person {
    public:
        string name;    // 姓名
        int age;    // 年龄

        // write your code here......
         Person (string name1, int age1){//Person pp(string name1, int age1){
            this->name = name1;
            this->age = age1;
        }

        void showPerson() {
            cout << name << " " << age << endl;
        }
};

int main() {

    string name;
    int age;

    cin >> name;
    cin >> age;

    Person p(name, age);
    p.showPerson();

    return 0;
}

cpp41.(深)拷贝构造函数

只需要看中间/的部分

#include <iostream>
#include <cstring>
#pragma warning(disable : 4996)
using namespace std;

class Person {

    public:
        char* name; // 姓名
        int age;    // 年龄

        Person(const char* name, int age) {
            this->name = new char[strlen(name) + 1];
            strcpy(this->name, name);
            this->age = age;
        }

         write your code here......
        // 深拷贝,对比👆上面的构造函数
        Person(const Person& p) {/const Person& p
            this->name = new char[strlen(p.name) + 1];name--->p.name
            strcpy(this->name, p.name);
            this->age = p.age;age---->p.age
        }        
		//
        void showPerson() {
            cout << name << " " << age << endl;
        }

        ~Person() {
            if (name != nullptr) {
                delete[] name;
                name = nullptr;
            }
        }

};

int main() {

    char name[100] = { 0 };
    int age;

    cin >> name;
    cin >> age;

    Person p1(name, age);
    Person p2 = p1;

    p2.showPerson();

    return 0;
}

cpp62. 数组类的拷贝构造函数

又是一道没用过只能先粘贴过来的题。。。

#include<bits/stdc++.h>
using namespace std;
class Array{
	private:
		int n;//数组大小 
		int *a;//数组 
	public:
		Array(){
			cin>>n;
			a=new int [n];
			for (int i=0;i<n;i++) cin>>a[i];
		}
		~Array(){
			delete []a;
		}
		int getlen(){
			return n;
		}
		int get(int i){
			return a[i];
		}
		// 拷贝构造函数
        Array(Array &array){
            delete[] a;
            n = array.getlen();
            a =  new int[n];
            for(int i = 0 ; i < n; i++) a[i] = array.get(i);
        }
    
        
		void show(){
			for (int i=0;i<n;i++) cout<<a[i]<<' ';
		}
};
int main(){
	Array a;
	Array b=a; 
	b.show();
	return 0;
}

cpp42. 友元全局函数

#include <iostream>
using namespace std;

class Person {
    // write your code here......
    friend void showAge(Person& p);
    ///友元声明在public或private效果是相同的

    public:
        Person(int age)  {this->age = age;}
    private:
        int age;
};

void showAge(Person& p) { cout << p.age << endl;}

int main() {
    Person p(10);
    showAge(p);
    return 0;
}

cpp63. 友元类

当希望一个类可以存取另一个类的私有成员时,可以将该类声明为另一类的友元类。定义友元类的语句格式如下:friend class 类名;

#include<bits/stdc++.h>
using namespace std;
class phone{
	// write your code here......
	friend class myphone;
	//只有以上这一句
	private:
		int price;
	public:
		phone(int x){
			price=x;
		}
}; 
class myphone{
	private:
		phone a;
	public:
		myphone(int x):a(x){//
		}
		int getprice(){
			return a.price;
		}
};
int main(){
	int p;
	cin>>p;
	myphone a(p);
	cout<<a.getprice();
	return 0;
}

cpp43-64. 加号运算符重载

定义:
(注意使用时后面没有参数,但是定义时有;函数的类型可调整,例如>可以为bool函数)
Time operator+ (Time &t)
Time sum;
sum.hours = t.hours + hours
调用:
Time t3 = t1 + t2;

#include <iostream>
using namespace std;

class Time {

    public:
        int hours;      // 小时
        int minutes;    // 分钟

        Time() {
            hours = 0;
            minutes = 0;
        }

        Time(int h, int m) {
            this->hours = h;
            this->minutes = m;
        }

        void show() { cout << hours << " " << minutes << endl;        }

        // write your code here......
        Time operator+ (Time &t){
            Time sum;
            sum.hours = t.hours + hours + (t.minutes + minutes)/60;
            sum.minutes =(t.minutes + minutes)%60;
            return sum;
        }
        

};

int main() {

    int h, m;
    cin >> h;
    cin >> m;

    Time t1(h, m);
    Time t2(2, 20);

    Time t3 = t1 + t2;
    t3.show();
    
    return 0;
}

cpp44. 子类中调用父类构造

描述
有父类 Base,内部定义了 x、y 属性。有子类 Sub,继承自父类 Base。子类新增了一个 z 属性,并且定义了 calculate 方法,在此方法内计算了父类和子类中 x、y、z 属性三者的乘积。请补全子类构造方法的初始化逻辑,使得该计算逻辑能够正确执行。
输入描述:
三个整数:x, y, z
输出描述:
三个整数的乘积:xyz

#include <iostream>
using namespace std;

class Base {

    private:
        int x;
        int y;

    public:
        Base(int x, int y) {
            this->x = x;
            this->y = y;
        }
        int getX() {  return x;   }
        int getY() {  return y;   }
};

class Sub : public Base {///
    private:
        int z;
    public:
        // write your code here
        Sub(int x, int y, int z) :Base(x,y) {
            this->z = z;      
        }
  ///

        int getZ() {return z;  }

        int calculate() {return Base::getX() * Base::getY() * this->getZ();    }

};

int main() {

    int x, y, z;
    cin >> x;
    cin >> y;
    cin >> z;
    Sub sub(x, y, z);
    cout << sub.calculate() << endl;
    return 0;
}

cpp65(类似45). 重写长方体

描述:
现在有长方形类(rectangle),请以此为基类构建长方体类(cuboid)并实现求体积的getvolume方法

输入描述:
输入三个整数x,y,zx,y,z分别表示长宽高。
输出描述:
输出长方体的体积。

输入:
3 2 1
输出:
6

#include<bits/stdc++.h>
using namespace std;
class rectangle{
	private:
		int length,width;
	public:
		rectangle(int x,int y){
			length=x;
			width=y;
		}
		void set(int x,int y){
			length=x;
			width=y;
		}
		int area(){
			return length*width;
		}
};
class cuboid:public rectangle{
	private:
		int height;
	public:
		// write your code here...
		cuboid (int x,int y,int z):rectangle(x,y){逐字背写
            rectangle(x,y);不能写在这里
            height = z;///or this->
        }
        int getvolume(){
            int vol = area() * height;
            return vol;
        }
    //
};
int main(){
	int x,y,z;
	cin>>x>>y>>z;
	cuboid a(x,y,z);
	cout<<a.getvolume();
	return 0;
}

cpp66.长方体面积

比上一题多了:
子类的构造函数继承于父类构造函数的写法、子类里写父类的同名函数并调用、子类使用父类的参数
题目:现在有长方形类(rectangle),请以此为基类构建长方体类(cuboid)并实现求表面积的area方法。

#include<bits/stdc++.h>
using namespace std;
class rectangle{
	private:
		int length,width;
	public:
		rectangle(int x,int y){
			length=x;
			width=y;
		}
		void set(int x,int y){
			length=x;
			width=y;
		}
		int getlength(){			return length;		}
		int getwidth(){			return width;		}
		int area(){			return length*width;		}
};
class cuboid:public rectangle{//在此处声明父对象用到了public,不影响里面也有public和private
	private:
		int height;
	public:
		// write your code here...
		cuboid (int x, int y, int z):rectangle(x, y){//子类的构造函数继承于父类构造函数的写法
            height = z;            
        }
        int area(){//注意不能调用this->area()否则调用自身,而要用如下的,明确调用的是父类的同名函数
            return 2*(this->rectangle::area() +this->height*this->getlength() + this->height*this->getwidth() );///此处的this不能省
                
        }/
        
};
int main(){
	int x,y,z;
	cin>>x>>y>>z;
	cuboid a(x,y,z);
	cout<<a.rectangle::area()<<'\n'<<a.area();
	return 0;
}

cpp45. 重写子类计算逻辑

描述
在父类 Base 中定义了计算方法 calculate(),该方法用于计算两个数的乘积(X*Y)。
请在子类 Sub 中重写该方法,将计算逻辑由乘法改为除法(X/Y)。注意,当分母为0时输出“Error”。

输入:
6
2
输出:
3

#include <iostream>
using namespace std;

class Base {

private:
    int x;
    int y;

public:
    Base(int x, int y) {
        this->x = x;
        this->y = y;
    }
    int getX() {        return x;    }
    int getY() {        return y;    }
    void calculate() {
        cout << getX() * getY() << endl;
    }

};
// write your code here......
class Sub : public Base {/注意是多了个【: public Base】
    public 在class定义中不能缺
    public:
    Sub(int x, int y): Base(x,y){}///构造函数!
    
    ///重写函数:直接复制,只是加了错误提示
    ///以及把 getY() 换成 Base::getY()
    void calculate() {
        if(Base::getY()==0)cout<<"Error"<<endl;
        else  cout << Base::getX() / Base::getY() << endl;
    }
};

int main() {

    int x, y, z;
    cin >> x;
    cin >> y;
    Sub sub(x, y);
    sub.calculate();
    
    return 0;
}

cpp46. 多态,virtual,某函数的父类声明、子类重载

多态实现计算器功能
题意整理。
给定一个父类BaseCalculator,子类AddCalculator和SubCalculator继承自BaseCalculator。
要求BaseCalculator中提供getResult方法,子类AddCalculator实现两个成员相加,子类SubCalculator实现两个成员相减。
方法:多态
1.解题思路
在父类BaseCalculator中,声明 getResult方法,并添加标识符virtual
在子类AddCalculator中 重载 getResult方法,实现相加功能。
在子类SubCalculator中 重载 getResult方法,实现相减功能。

#include <iostream>
using namespace std;

class BaseCalculator {
    public:
        int m_A;
        int m_B;
        // write your code here......
    virtual int getResult();// virtual ///no {}
        
};

// 加法计算器类
class AddCalculator : public BaseCalculator {/// : public BaseCalculator 
    // write your code here......
    int getResult(){
        return m_A + m_B;重载父类的变量,不用加 BaseCalculator.
    }
};

// 减法计算器类
class SubCalculator : public BaseCalculator {
    // write your code here......
    int getResult(){
        return m_A -  m_B;
    }    
};


int main() {

    BaseCalculator* cal = new AddCalculator;
    cal->m_A = 10;
    cal->m_B = 20;
    cout << cal->getResult() << endl;
    delete cal;

    cal = new SubCalculator;
    cal->m_A = 20;
    cal->m_B = 10;
    cout << cal->getResult() << endl;
    delete cal;

    return 0;
}

cpp67. 多态实现求长方体面积体积

似乎只是比66多了个virtual?
题目:现在有长方形类(rectangle),和以此为基类构建的长方体类(cuboid),运用多态在两个类中实现getval方法,在长方形类中是求面积功能,在长方体类中是求体积功能。

#include<bits/stdc++.h>
using namespace std;
class rectangle{
	private:
		int length,width;
	public:
		rectangle(int x,int y){			length=x;			width=y;		}
		void set(int x,int y){			length=x;			width=y;		}
		int getlength(){			return length;		}
		int getwidth(){			return width;		}
		// write your code here...
        virtual int getval (){//多态关键字virtual
            return length*width;//最好加上this->?因为答案里都是这么写的
        }
};
class cuboid:public rectangle{
	private:
		int height;
	public:
		cuboid(int x,int y,int z):rectangle(x,y){
			height=z;
		}
		// write your code here...
        virtual int getval(){//多态关键字virtual,子类重写
            return this->height * this->rectangle::getval();
        }///
};
int main(){
	int x,y,z;
	cin>>x>>y>>z;
	cuboid a(x,y,z);
	rectangle b(x,y);
	
	rectangle *p=&b;
	cout<<p->getval()<<'\n';
	
	p=&a;
	cout<<p->getval();
	return 0;
}

STL

cpp47. 迭代器vector< int >::iterator 遍历vector< int >

描述:
键盘输入 5 个整数,将这些数据保存到 vector 容器中,采用正向迭代器和反向迭代器分别遍历 vector 中的元素并输出。

重点:
#include < vector >;
vector< int >的初始化;
auto iter的表述(注意vector< int >::iterator和arr无关,独立的)

#include <iostream>
// write your code here......
#include <vector>
using namespace std;

int main() {
    // write your code here......
/*     char a = '1';
    vector<char> ch;
    while (cin>> a) ch.push_back(a);
    for(int i = 0; i<5; i++) cout<<ch[i]<<" ";
    cout<<endl;  ///12340,-----> 可以cin>>'0'
    int j = 0;
    while(ch[j]){
        cout<<ch[j]<<" ";
        j++;
    }//12340,--->'0'=true, != 0==false
    cout<<endl;  */
   vector<int> arr;
    for(int i = 0; i <5; i++){
        int num = 0;
        cin>>num;
        arr.push_back(num);
    }
    auto iter = arr.begin();///or  vector<int>::iterator
    while(iter!= arr.end()){
        cout<< *iter <<" ";
        iter++;
    }
    cout<<endl;12345
    while(iter!= arr.begin()){
        iter--;or 05432
        cout<< *iter <<" ";
        
    }
    cout<<endl;
    return 0;
}

cpp68. 迭代器set::iterator 遍历set

描述
键盘输入 5 个整数,将这些数据保存到set中,采用迭代器正向遍历set中的元素并输出。

示例1
输入:
3 4 5 1 2
输出:
1 2 3 4 5

#include<bits/stdc++.h>
using namespace std;
int main(){
	set<int>s;
	// write your code here......
    //如何将数据保存到set中?不存在下标索引,也没有push_back: 用insert
	for (int i=0; i<5; ++i){
        int num;
        cin>>num;
        //输入不是push_back
        s.insert(num);
    }
    //set自动将数据从大到小排序,且不重复
    for(auto iter = s.begin(); iter!=s.end();++iter){
        cout<<*iter<<" ";
    }
	return 0;
}

cpp48. deque的前后加元素 + 遍历元素

描述:
请设计一个排队程序,用户有普通客人和 VIP 客人之分,VIP 客人不排队(即 VIP 客人在队列头部),请将已有的guest1和guest2放入队列中(guest1排在guest2前),并将VIP客人新增至队列头部。

注意点:
元素是class类型
#include < deque >

#include <iostream>
#include <deque>
using namespace std;
class Guest {
public:
    string name;
    bool vip;
    Guest(string name, bool vip) {
        this->name = name;
        this->vip = vip;
    }
};
int main() {
    Guest guest1("张三", false);
    Guest guest2("李四", false);
    Guest vipGuest("王五", true);
    deque<Guest> deq;
、、、、关注此部分
    // write your code here......不是“程序”,不用考虑普适性(任意输入etc)
    deq.push_back(guest1);
    deq.push_back(guest2);
    deq.push_front(vipGuest);
    
    for (Guest g : deq) {此处的遍历语句是普适的:到空为止
        cout << g.name << " ";
    }

    return 0;
}

cpp69. iter 倒序遍历:最后k个元素

#include<bits/stdc++.h>
using namespace std;
int main(){     int n,k;     vector<int>a;     // write your code here......     cin>>n>>k;
    for(int i=0,x;i<n;i++){
    while(cin>>x){
         a.push_back(x);  //push_back成员函数在vector容器尾部添加一个元素
    }         
}     int i=0;
///
    for(vector<int>::iterator it=a.end()-1;it!=a.begin(),i<k;it--,i++){
        cout<<*it<<' ';
    }
    cout<<endl;     
    return 0;
}

cpp51. for_each() 和 sort(. . great< int >)

for_each()

需要#include < algorithm >
事实上是個 function template,源码link:http://www.cplusplus.com/reference/algorithm/for_each/?kw=for_each

template<typename InputIterator, typename Function>
Function for_each(InputIterator beg, InputIterator end, Function f) {
  while(beg != end) 
    f(*beg++);
}

for_each(v.begin(), v.end(), print);
///print在此处不需要加(),本来是void print(int x)

sort(. . great< int >)

sort(v.begin(),v.end(), greater());//降
sort(v.begin(), v.end(),less());//升///缺省less则默认升序

描述:
键盘输入 5 个整数,使用 vector 进行存储,使用 STL 排序算法对元素进行排序(从大到小),再使用 STL 遍历算法输出元素。(元素和元素之间使用空格隔开)

输入:
89
90
78
66
45
输出:
90 89 78 66 45

#include <iostream>
#include <vector>
// write your code here......
#include <algorithm>
using namespace std;
void print(int x){
    cout<<x<<" ";
}
int main() {
    int num;
    vector<int> v;
    for (int i = 0; i < 5; i++) {
        cin >> num;
        v.push_back(num);
    }
/// write your code here......
    sort(v.begin(),v.end(), greater<int>());//降
    ///sort(v.begin(), v.end(),less<int>());//升///缺省less则默认升序
    for_each(v.begin(), v.end(), print);///print在此处不需要加()

    return 0;
}

知识点综合题

cpp53. 计算所得税

将变量从private“变成”public
if直到最后一个else之间都不要有分号!!
cout<<fixed<<setprecision(1) ;#include < iomanip >;小数要用double
sort,cmp,vector;#include < algorithm >
class以外定义函数,使用class中变量;构造函数;class以内定义函数
for_each
#include <iostream>
// write your code here......
#include <string>
#include <iomanip>/cout<<fixed<<setprecision(1)
#include <algorithm>///sort
#include <vector>sort要用到!
using namespace std;

class Employee {

    private:
        string name;埋坑了↓
        double salary;
    // write your code here......
    public:
        Employee (string n, double s){构造函数
            this->name = n;
            this->salary = s;
        }
        ///this->name 也可以// ↑ //获取名字,将其从private变成public
        string getName(){return name;}
        // ↑ //获取薪水,注意是小数,要用double
        double getSalary(){return this->salary;}
    
        double Tax (){
            double sal = this->salary - 3500;
            double tax = 0;
            double shuilv = 0;
            double susuan = 0;
            
            if。。。直到最后一个else之间都不要有分号!!
            if(sal <= 1500){shuilv = 0.03; susuan = 0;}
            else if( sal <= 4500){shuilv = 0.10; susuan = 105;}
            else if( sal <= 9000){shuilv = 0.20; susuan = 555;}
            else if( sal <= 35000){shuilv = 0.25; susuan = 1005;}
            else if( sal <= 55000){shuilv = 0.30; susuan = 2755;}
            else if( sal <= 80000){shuilv = 0.35; susuan = 5505;}
            else {shuilv = 0.45; susuan = 13505;};///last ; ok
            
            tax = sal * shuilv -susuan;// (sal - 3500)  WRONG,加强题意理解
            return tax;
        }
        
        void shuchu(){
            string n = this->name;
            double t = this->Tax();
            cout<<fixed<<setprecision(1)<< n <<"应该缴纳的个人所得税是:"<< t << endl;
        }
    

};
cmp 必须在 class 以外
        bool cmp(Employee &e1, Employee &e2){
            return e1.getSalary() > e2.getSalary();// ↑ //e1.salary WRONG,因为被定义为了private
        }

int main() {

    // write your code here......
    Employee  emp1("张三", 6500);
    Employee  emp2("李四", 8000);
    Employee  emp3("王五", 100000);

    vector<Employee> arre;
    arre.push_back(emp1);
    arre.push_back(emp2);
    arre.push_back(emp3);这里只能手动输入
    //    emp3.shuchu();、×、可以避免的手动输入
    sort可以比较(排序)二者以上的多元函数某元的大小,前提是都存进vector
    sort(arre.begin(), arre.end(), cmp);
    
    for(int i = 0 ; i < arre.size(); i++)
        arre[i].shuchu();
    /*
    也可以这样,其中 void print(Employee& e) 也在class以外
    for_each(vec.begin(),vec.end(),print);
    */
    return 0;
}

cpp54. 计算器类-再看

答案

#include <iostream>
using namespace std;

int main() {

    char str[100] = { 0 };
    cin.getline(str, sizeof(str));

    // write your code here......
    int fs=0,s1=0,s2=0,j;
    if(str[0]=='a'||str[0]=='A')fs=1;
    else if(str[0]=='s')fs=2;
    else if(str[0]=='m')fs=3;
    else if(str[0]=='d')fs=4;
    
    for(int i=4;str[i]!=' ';i++,j=i)
        if( isdigit(str[i]) ) s1=s1*10+(str[i]-'0');
    while(!isdigit(str[j]))j++;
    for(;str[j]!='\0';j++)
        if( isdigit(str[j]) ) s2=s2*10+(str[j]-'0');

    if(!s2){cout<<"Error"<<endl;exit(0);}
    switch(fs){
        case 1:cout<<s1+s2<<endl;break;
        case 2:cout<<s1-s2<<endl;break;
        case 3:cout<<s1*s2<<endl;break;
        case 4:cout<<s1/s2<<endl;break;
    }
    return 0;
}

自己的

#include <iostream>
#include <cstring>///+c better
using namespace std;

int main() {

    char str[100] = { 0 };
    cin.getline(str, sizeof(str));
    // write your code here......
    char opr[3] = {0};
    char x[999] = {0};
    char y[999] = {0};
    int i = 0;
    int xn = 0, yn = 0;
    int xx = 0, yy = 0;///整数范围为[-100, 100]
    bool fx = 1, fy = 1;
    while(str[i] != '\0'){
        if(str[i] >='a' && str[i]<='z'||str[i] >='A' && str[i]<='Z'){//
            opr[i] = str[i];
        } 
        else if(str[i] ==' ')break;
        i++;
    }           // cout<<opr[i];//add
    
 /* */  
    int xi = 0;
    while(str[i] != '\0'){
        i++;
        cout<<"stri: "<<str[i]<<" ";///i-- ----> stri: d stri:  0
        if(str[i] >='0' && str[i]<='9') {
            x[xi] = str[i]; 
            xi++;
            xn++; 
            cout<<x[xi]<<"xii";never cout
        }
        else if(str[i]=='-')fx = 0;
        else if(str[i] ==' ')break;
        i++;        
    }

    int yi = 0;
    while(str[i] != '\0'){
        if(str[i] >='0' && str[i]<='9') {y[i] = str[i]; yi++; yn++;}
        else if(str[i]=='-')fy = 0;
        i++;        
    }    
    for(int i = 0; i<xn; i++){
        xx = x[i] +xx*10;
    }
    if(fx == 0) xx*=-1;
    for(int i = 0; i<yn; i++){
        yy = y[i] +yy*10;
    } 
    if(fy == 0) yy*=-1;
    
    //cout<<"xx: "<<xx<<"yy: "<<yy<<endl;
    
    switch(opr[0]){
        case 'A': case 'a':
            cout<<xx+yy<<endl; break;
        case 'S': case 's':
            cout<<xx-yy<<endl; break;
        case 'M': case 'm':
            cout<<xx*yy<<endl; break;
        case 'D': case 'd':
            if(yy == 0){cout<<"Error"<<endl; break;}
            else {cout<<xx/yy<<endl; break;};
            
    }
    

    return 0;
}
  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值