当前位置:   article > 正文

【牛客题霸】语法篇 - C++入门72题_(long)array[7] << 56

(long)array[7] << 56

数字和基本语法

一些笔记: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
  • 1
  • 2
  • 3

方法二:直接写

double x;
int y;
if(d>=0) y = d+0.5;
    else y = d- 0.5;
cout << y <<endl;
  • 1
  • 2
  • 3
  • 4
  • 5

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

cpp8. 取小数点后1位

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

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

取小数点后1位 :

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

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

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

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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

cpp12.for循环の跳步:

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

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

cpp17 如何输出“100.0 50.0”

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

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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

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

另外:
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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

cpp21.冒泡排序

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

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

重点在于 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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

复杂度分析:
时间复杂度: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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

复杂度分析:
时间复杂度: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         //没有逗号
    };
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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

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

int* arr = new int[n];
  • 1

解析用的是

int* arr = new int[n];
  • 1

之后一切如常。。。

#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;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

创建二维数组

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

    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++) {
            ...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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--;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

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

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;
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

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

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

字符串

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

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

C-风格字符串

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

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

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

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

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

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

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"}
  • 1
  • 2
  • 3
  • 4
显著区别:

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

string str1;
string str2 = "hello";
str1 = str2;
  • 1
  • 2
  • 3

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

string str3 = str1 + str2;
str1 += str2;
  • 1
  • 2

③ 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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

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;

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

不用指针的做法:

...
#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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
不用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;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

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;
       ...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

自己的做法:

#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;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

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;
    }

  • 1
  • 2
  • 3
  • 4

复杂度分析:
时间复杂度: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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

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;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

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

#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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

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;
    }
  • 1
  • 2
  • 3
#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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

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;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

自己写的,居然也行

#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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

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;
     }
  • 1
  • 2
  • 3
  • 4

整体代码如下:

#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;
   
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

面向对象

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78

cpp40. 构造函数

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

Person (string name1, int age1){//Person pp(string name1, int age1){
            this->name = name1;
            this->age = age1;
        }
  • 1
  • 2
  • 3
  • 4

构造函数这样调用:

    Person p(name, age);
  • 1

全文:

#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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

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......
        // 深拷贝,对比声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读