C++初级语法或编程小技巧
C++语法篇
c++复学习!
sizeof()输出变量占的字节数
sizeof(char) =1
sizeof(int)=4
sizeof(long)=8
sizeof(long long)=8
sizeof(double)=8
实现四舍五入
头文件
ceil()向上取整
floor()向下取整
round()四舍五入
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double a=2.3;
cout<<ceil(a)<<endl;//向上取整
cout<<(a>(int)a?(int)(a+1):(int)a)<<endl;//不用函数的向上取整,意义:可能会有0.9之类需要向上取整
cout<<(int)a+1<<endl;//我觉得上面写法和下面是等效的
cout<<floor(a)<<endl;//向下取整
cout<<(int)a<<endl;//强制类型转换不管怎样只取整数部分=向下取整
cout<<round(a)<<endl;//四舍五入
cout<<(a>(int)(a+0.5)?(int)a:(int)(a+1))<<endl;//不用函数四舍五入
}
输出时用条件句
要带括号哟
#include <iostream>
using namespace std;
int main()
{
int a,b;
cin>>a;
cin>>b;
cout<<(a>b?a:b);//看这里
return 0;
}
幺幺好好审题呀!
小数点后取几位
#include <iostream>
#include <iomanip>//头文件这里
using namespace std;
int main() {
double price;
cin >> price;
double cost = 0.0;
// write your code here.......
if(price<500&&100<=price) cost=price*0.9;
else if(price<2000&&500<=price) cost=price*0.8;
else if(price<5000&&2000<=price) cost=price*0.7;
else if(price<=5000) cost=price*0.7;
else cost=price;
cout << setiosflags(ios::fixed) << setprecision(1) << cost << endl;
return 0;
}
#include
cout << setiosflags(ios::fixed) << setprecision(1) << cost ;
这里的setioflags(ios::fixed)里ios一定要写
setprecision(1)这是保留几位小数
switch()语句
多个case有相同的下一步操作时
#include <iostream>
using namespace std;
int main() {
int month;
cin >> month;
// write your code here......
switch(month){
case 12:
case 1:
case 2:cout<<"冬季";break;
case 3:
case 4:
case 5:cout<<"春季";break;
case 6:
case 7:
case 8:cout<<"夏季";break;
case 9:
case 10:
case 11:cout<<"秋季";break;
default:cout<<"不合法";
}
return 0;
}
运算循环要注意
循环里某些变量的初始更新
运算里有用到pow()函数,记得把算式左边的变量定义为double型,否则计算结果可能回和预设有出入
#include <iostream>
#include <cmath>
using namespace std;
int main() {
// write your code here......
int a,b;
for(int i=100;i<=999;i++){
a=i;
double sum=0;//重点在这里!
while(a){
b=a%10;
sum=sum+pow(b,3);
a=a/10;
}
if(sum==i) cout<<i<<endl;
}
return 0;
}
注意循环的增加数的位数的处理技巧
注意某些整数可能需要long long
审题朋友!
题设:
有数列为:9,99,999,…,9999999999(10个9)。要求使用循环结构编写程序计算此数列的和,并在控制台输出结果。
#include <iostream>
using namespace std;
int main() {
// write your code here......
long long sum=0;
long long num=0;
for(int i=1;i<=10;i++){
num=num*10+9;//看这里!
sum=sum+num;
}
cout<<sum;
return 0;
}
注意审题
输入描述:
输入小球下落的高度和落地的次数(先输入小球初始高度再输入反弹次数)
输出描述:
输出小球第 n 次 落地时经过的距离和第 n 次反弹的高度(保留小数点后1位)
示例1
输入:
100 1
复制
输出:
100.0 50.0
i
i
i i
i i i
注意第n次落地走过的距离:一落一弹为一完整
落地时走过距离=走过完整的-该次弹起的
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// 下落的高度和落地的次数
double h;
double sum=0;
int n;
cin >> h;
cin >> n;
for(int i=1;i<=n;i++){
h=h/2;
sum=sum+h*3;
}
cout<<setiosflags(ios::fixed)<<setprecision(1)<<sum-h<<" ";
cout<<setiosflags(ios::fixed)<<setprecision(1)<<h;
return 0;
}
练习一种做编程题的模式
1.看到题目先花5分钟分析
考虑算法
考虑数据结构
考虑变量类型
2.开始10分钟编码
没有思路或者ac失败直接看题解
判断一个数是不是素数
质数就是素数,1既不是质数也不是合数。
#include <iostream>
#include <cmath>
using namespace std;
int isPrime(int n){
if(n==1||n==4) return 0;
else if(n==2||n==3) return 1;
else if(n%2==0&&n>4) return 0;
else{
double temp=sqrt(n);
for(int i=5;i<=temp;i=i+2){
if(n%i==0) return 0;
}
return 1;
}
}
int main() {
// write your code here......
int num;
cin>>num;
if(isPrime(num)) cout<<"是质数";
else cout<<"不是质数";
return 0;
}
字符串操作
拼接字符串
string s1,s2,s3;
s1=“cvbjju”;
s2=“tfyghuj"
s3=s1+s2;
字符串里找某个子串出现次数
用cstring里的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;
// write your code here......
string str1(str);
string str2(substr);
int i=0;
while(str1.find(str2,i)!=-1){
count++;
i=str1.find(str2,i)+1;
}
cout << count << endl;
return 0;
}
时间复杂度:
find函数的时间复杂度是O(n+m)
可能要找n次
总的时间复杂度是O(n*(n+m))
空间复杂度:需要额外的空间是常数级别的,所以是O(1)
叮咚
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;
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;
}
输入的字符串是一个字符数组,采用getline函数输入,这样会在输入的末尾增加一个’\0’表示字符串的结束,如果长度小于数组长度,输入所有字符后加’\0’,如果长度大于数组长度,截断输入的前面部分再在最后加’\0’
字符串里统计某类字符出现次数
#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......
int i=0;
while(str[i]!='\0'){
if(isdigit(str[i])) digits++;
else if(isalpha(str[i])) chars++;
else if(isblank(str[i])) whitespace++;
else others++;
i++;
}
cout << "chars : " << chars
<< " whitespace : " << whitespace
<< " digits : " << digits
<< " others : " << others << endl;
return 0;
}
这里运用了很多在type.h库里的函数,已经包含在iostream里。总结一下:
isupper©:c是大写字母
islower©:c是小写字母
isalpha©:函数isupper©或islower©为真;
isdigit©:c是十进制数字;
isxdigit©:c是十六进制数字;
isalnum©:函数isalpha©或isdigit©为真;
isspace©:c是空格、换页符、换行符、回车符、横向制表符或纵向制表符
iscntrl©:c为控制字符
指针操作
利用指针遍历数组
#include <iostream>
using namespace std;
int main() {
int arr[6] = { 0 };
int* ptr = arr;
int len = sizeof(arr) / sizeof(int);
for (int i = 0; i < len; i++) {
cin >> arr[i];
}
for(int i=0;i<len;i++){
if(i!=len-1) cout<<*ptr<<" ";
else cout<<*ptr;
ptr++;
}
return 0;
}
注意不要用while(ptr!=NULL)
字符指针实现求字符串长度
#include <iostream>
using namespace std;
int main() {
char str[100] = { 0 };
cin.getline(str, sizeof(str));
// write your code here......
char* p=str;
int len=0;
while(*p!='\0'){//这里要注意
len++;
p++;
}
cout<<len;
return 0;
}
利用指针复制字符串
#include <iostream>
using namespace std;
int main() {
char str[30] = { 0 };
cin.getline(str, sizeof(str));
int m;
cin >> m;
// write your code here......
char copystr[30] = { 0 };
char* p = str + m - 1; //指向字符数组第m个元素
char* q = copystr;
while(*p != '\0'){ //直到字符串结果
*q=*p;
q++;
p++;; //两边指针都后移
}
cout<<copystr<<endl;
return 0;
}
数组
动态数组
//创建动态数组
int n;
cin >> n;
int num[n];
把数组里某类元素往后移,用类似冒泡的办法。
如:
有一个数组 int arr[n],要求写一个函数:void func(int *p, int n);将数组 arr 中为 0 的元素都移至数组末尾,将非 0 的元素移至开始(保持原来的顺序不变)。
例如:
数组中元素原来是:1 0 3 4 0 -3 5
经过 func 处理后:1 3 4 -3 5 0 0
#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......
for(int i=0;i<n-1;i++){
for(int j=i;j<n-i;j++){
if(p[j]==0) {//变通在这里
int temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
}
}
}
}
比较字符串大小
编写一个函数 int mystrcmp(const char * src, const char * dst),用于比较两个字符串的大小(自己实现strcmp()函数)。要求如果字符串src大于字符串dst返回 1,小于返回 -1,相等返回 0。
输入描述:
键盘录入 2 个长度小于 100 的字符串
输出描述:
输出调用 mystrcmp() 函数返回的结果
示例1
输入:
hello
helloworld
输出:
-1
#include <iostream>
using namespace std;
int mystrcmp(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 flag=0;
while(*src!='\0'&&*dst!='\0'){
if(*src>*dst){
flag=1;
break;
}
else if(*src<*dst){
flag=-1;
break;
}
src++;
dst++;
}
if(*dst=='\0'&&*src!='\0') flag=1;
if(*src=='\0'&&*dst!='\0') flag=-1;
return flag;
}
交换两个数
指针交换两个数
#include <iostream>
using namespace std;
// write your code here......
void Swap(int *p,int *q){
int t=*p;
*p=*q;
*q=t;
}
int main() {
int m, n;
cin >> m;
cin >> n;
// write your code here......
Swap(&m,&n);
cout << m << " " << n << endl;
return 0;
}
采用引用方式交换两个数
#include <iostream>
using namespace std;
// write your code here......
void swap(int &m,int &n){
int p=m;
m=n;
n=p;
}
int main() {
int m, n;
cin >> m;
cin >> n;
// write your code here......
swap(m,n);
cout << m << " " << n << endl;
return 0;
}
数列找规律
1.不死兔问题
骂骂自己
这个题目只要把输出规律用纸笔写下来,找找规律就行了,就是懒!
1.不死兔问题
有一对兔子,从出生后第 3 个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问第n个月的兔子对数为多少?
n的范围是1-20
#include <iostream>
using namespace std;
int getSum(int n);
int main() {
int n;
cin >> n;
cout << getSum(n) << endl;
return 0;
}
int getSum(int n) {
if(n==1||n==2) return 1;
else{
int sum=0;
int pre1=1,pre2=1;
for(int i=3;i<=n;i++){
sum=pre1+pre2;
pre1=pre2;
pre2=sum;
}
return sum;
}
}
走出舒适区之用递归写法:
#include <iostream>
using namespace std;
int getSum(int n);
int main() {
int n;
cin >> n;
cout << getSum(n) << endl;
return 0;
}
int getSum(int n) {
if(n==1||n==2) return 1;
else return getSum(n-1)+getSum(n-2);
}
类
类的构造函数
构造函数和类同名
描述 现有一个人类(Person),成员变量:姓名(string name)和年龄(int age),请给 Person
添加一个支持两个参数的构造函数,并对姓名和年龄两个成员进行初始化。 输入描述: 键盘输入用户名和年龄 输出描述: 通过 Person
类的showPerson()成员方法输出 Person 对象的姓名和年龄,中间使用空格隔开
#include <iostream>
#include <string>
using namespace std;
// Person类
class Person {
public:
string name; // 姓名
int age; // 年龄
Person(string name, int age){
this->name=name;
this->age=age;
}
// write your code here......
void showPerson() {
cout << name << " " << age << endl;
}
};
int main() {
string name;
int age;
cin >> name;
cin >> age;
Person p(name, age);
p.showPerson();
return 0;
}
类的拷贝函数
知识点
初始化类有两种方式,一种叫构造函数,函数名称为类名,参数是成员变量的输入值,没有返回值,作用是输入成员变量的初始值,赋值给成员变量,这是用变量值初始化类;另一种叫拷贝构造函数,函数名称也是类名,与拷贝构造不同的是,它的参数是一个类,就是就是我们当前这个类,它的作用是用参数给的这个类的成员变量复制赋值给当前类的成员变量。
描述 现有一个 Person 类,成员变量:姓名(string name)和年龄(int age),请给 Person
添加一个拷贝构造函数,让程序能够正确运行。
输入描述: 键盘输入用户名和年龄
输出描述: 通过 Person类的showPerson()成员方法输出 Person 对象的姓名和年龄,中间使用空格隔开
示例1
输入: zhangsan 20
输出: zhangsan 20
#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(Person& p){
this->age=p.age;
this->name=new char[strlen(p.name)+1];//注意去仿构造函数的写法
strcpy(this->name, p.name);
}
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;
}
友元全局函数
友元函数,把函数的声明放在类的里面同时在前面加上friend关键字,友元函数虽然不是类的成员函数,但是可以访问类的私有数据
#include <iostream>
using namespace std;
class Person {
// write your code here......
friend void showAge(Person &);//看这里
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;
}
运算符重载
运算符一般包含单目运算符、双目运算符合三目运算符,因此重载的函数一般形容"opertator运算符",返回的东西一般就是这个类的变量实例。
作为类成员函数重载:Time operator + (Time t) 非类成员函数 Time operator+ (Time t1,Time 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 t2){
int hour=this->hours+t2.hours;
int minute=this->minutes+t2.minutes;
hour=hour+minute/60;
minute=minute%60;
return Time(hour,minute);
}
};
/*
Time operator+ (Time t1,Time t2){
int hour=t2.hours+t1.hours;
int minute=t2.minutes+t1.minutes;
hour=minute/60+hour;
minute=minute%60;
return Time(hour,minute);
}
*/
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;
}
父类中调用子类构造
父类Base的变量都是private类型,不允许外界访问,因此我们我们只能调用父类的构造函数来初始化x和y变量,然后变量z初始化直接赋值即可。子类调用父类的构造函数我们直接将: Base(x, y)加在子类构造函数参数后面即可。
#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:
Sub(int x, int y, int z):Base(x,y) {
// write your code here
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;
}
注意时间复杂度和空间复杂度分析!
多态
完善下面的代码,使程序能够正常运行。要求 BaseCalculator 类中提供 getResult() 函数(无需实现),在 AddCalculator 类中实现两个成员相加(m_A + m_B),在 SubCalculator 类中实现两个成员相减(m_A - m_B)
给定一个父类BaseCalculator,子类AddCalculator和SubCalculator继承自BaseCalculator。要求BaseCalculator中提供getResult方法,子类AddCalculator实现两个成员相加,子类SubCalculator实现两个成员相减。
多态方法:
在父类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();//写个声明就好,不要有实现
};
// 加法计算器类
class AddCalculator : public BaseCalculator {
// write your code here......
public:
virtual int getResult(){
return m_A+m_B;
}
};
// 减法计算器类
class SubCalculator : public BaseCalculator {
// write your code here......
public:
virtual 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;
}
STL
迭代器正向和逆向遍历容器
让迭代器从begin()开始自增
让迭代器从end()开始自减
注意end()的时候什么都没有
#include <iostream>
// write your code here......
#include <vector>
using namespace std;
int main() {
// write your code here......
vector<int> num(5);
for(int i=0;i<5;i++){
cin>>num[i];
}
vector<int>::iterator it;
for(it = num.begin();it!=num.end();it++) cout<<*it<<" ";
cout<<endl;
for(it = num.end()-1;it!=num.begin()-1;it--) cout<<*it<<" ";
return 0;
}
以上是我的不标准写法。
下面是比较标准写法:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
int a;
while(cin >> a) //输入
v.push_back(a);
vector<int>::iterator iter = v.begin(); //迭代器指向vector第一个位置
while(iter != v.end()){ //从第一个位置遍历到尾
cout << *iter << " "; //输出
iter++;
}
cout << endl; //换行
while(iter != v.begin()){ //从尾遍历到头部
iter--;
cout << *iter << " ";
}
cout << endl;
return 0;
}
好吧其实好像也差不多
set去重
实现了红黑树(Red-Black Tree)的平衡二叉检索树的数据结构,在插入元素时,它会自动调整二叉树的排列,把该元素放到适当的位置,以确保每个子树根节点的键值大于左子树所有节点的键值, 而小于右子树所有节点的键值;另外,还得确保根节点的左子树的高度与有字数的高度相等,这样,二叉树的高度最小,从而检索速度最快。要注意的是,它不会重复插入相同键值的元素,而采取忽略处理。平衡二叉检索树的检索使用中序遍历算法,检索效率高于vector、和list的容器。 另外,采用中序遍历算法可将键值由小到大遍历出来,所以,可以理解为平衡二叉检索树在插入元素时,就会自动将元素按键值从小到大的顺序排列。 构造set集合的主要目的是为了快速检索,使用set前,需要在程序头文件中包含声明set
描述
从键盘获取一串字符串,要求去除重复的字符,请使用 set 解决。
输入描述:
键盘输入任意字符串
输出描述:
输出去重后的内容(直接按 set 的默认顺序输出字符即可)
#include <iostream>
// write your code here......
#include <set>
using namespace std;
int main() {
char str[100] = { 0 };
cin.getline(str, sizeof(str));
// write your code here......
set<char> myset;
int i=0;
while(str[i]!='\0'){
myset.insert(str[i]);
i++;
}
set<char>::iterator it;
for(it=myset.begin();it!=myset.end();it++){
cout<< *it;
}
return 0;
}
如果插入了重复的value会自动忽略。
用map统计某种字符在字符串出现次数
键盘输入一个字符串,统计字符串中各个字母字符的个数。例如:键盘输入"Hello World!",上述字符串中各个字母字符的出现的次数为:
H:1
e:1
l:3
o:2
W:1
r:1
d:1
要求使用map实现,键的排序使用map默认排序即可。
#include <iostream>
#include <map>
// write your code here......
using namespace std;
int main() {
char str[100] = { 0 };
cin.getline(str, sizeof(str));
map<char, int> mp;
for(int i = 0; str[i] != '\0'; i++){ //遍历字符串
if(isalpha(str[i])) //对于是字母的字符
mp[str[i]]++; //加入哈希表,并统计次数
}
for( auto iter = mp.begin(); iter != mp.end(); iter++) //遍历哈希表
cout << iter->first << ":" << iter->second << endl; //输出key与value
return 0;
}
学会用auto
使用算法排序
要引入头文件algorithm
sort(begin(),end(),greater< int >())从大到小排序
sort(begin(),end())从小到大排序
#include <iostream>
#include <vector>
#include <algorithm>
// write your code here......
using namespace std;
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>());
for(int i=0;i<v.size();i++){
cout<<v[i]<<" ";
}
return 0;
}
综合应用STL
给盛在STL容器里的结构体元素排序
1.vector, sort, cmp函数组合
用vector承载结构体元素
写好cmp函数
用sort(begin(),end(),cmp)给容器里的元素排序
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <vector>
// write your code here......
using namespace std;
class Employee {
private:
string name;
double salary;
// write your code here......
public:
Employee(string name,double salary){
this->name=name;
this->salary=salary;
}
double getTax()
{
double tax;
int num;
num=this->salary-3500;
if(num<=0) tax=0.0;
else if(0<num&&num<=1500) tax=num*0.03-0;
else if(1500<num&&num<=4500) tax=num*0.1-105;
else if(4500<num&&num<=9000) tax=num*0.2-555;
else if(9000<num&&num<=35000) tax=num*0.25-1005;
else if(35000<num&&num<=55000) tax=num*0.3-2755;
else if(55000<num&&num<=80000) tax=num*0.35-5505;
else tax=num*0.45-13505;
return tax;
}
string getName(){
return this->name;
}
double getSalary(){
return this->salary;
}
};
double cmp(Employee& e1,Employee& e2){
return e1.getSalary()>e2.getSalary();
}
int main() {
vector<Employee> v;
Employee e2("李四",8000);
Employee e3("王五",100000);
Employee e1("张三",6500);
v.push_back(e1);
v.push_back(e2);
v.push_back(e3);
sort(v.begin(),v.end(),cmp);
cout<<fixed<<setprecision(1);
for(auto it=v.begin();it!=v.end();it++ ){
cout<<it->getName()<<"应该缴纳的个人所得税是:"<<it->getTax()<<endl;
}
return 0;
}
2.用set
class myCompare {
public:
bool operator()(const Employee& e1, const Employee& e2) const {
return e1.getSalary() > e2.getSalary();
}
};
set<Employee,myCompare> s;//再给s插入
拆分字符串运算
键盘输入一个字符串,格式:运算方式 整数1 整数2,编写程序解析出字符串中的 3 部分内容,然后做相应的运算,并输出结果。
例如:
输入“add 10 20”,则做加法运算(10+20);
输入“sub 10 20”,则做减法运算(10-20);
输入“mul 10 20”,则做乘法运算(10*20);
输入“div 10 20”,则做除法运算(10/20),如果除数为 0,则不做运算,输出“Error”;
注意:运算方式忽略大小写,即 “add” 同 “Add”、“ADD”等。
输入描述:
键盘输入一个字符串,格式:运算方式 整数1 整数2
整数范围为[-100, 100]
输出描述:
输出运算后的结果(除法不考虑小数),如果除数为 0,则不做运算,输出“Error”
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[100] = { 0 };
cin.getline(str, sizeof(str));
char* msg[30] = { str, nullptr };
int i = 0;
while ((msg[i] = strtok(msg[i], " ")) && ++i);
char* op = msg[0];
int num1 = atoi(msg[1]);
int num2 = atoi(msg[2]);
if (strcasecmp(op, "add") == 0) {
cout << num1 + num2 << endl;
}
else if (strcasecmp(op, "sub") == 0) {
cout << num1 - num2 << endl;
}
else if (strcasecmp(op, "mul") == 0) {
cout << num1 * num2 << endl;
}
else if (strcasecmp(op, "div") == 0) {
if (num2 == 0) {
cout << "Error" << endl;
}
else {
cout << (double)num1 / num2 << endl;
}
}
return 0;
}
拆分字符串
char str[100] = { 0 };
cin.getline(str, sizeof(str));
char* msg[30] = { str, nullptr };
int i = 0;
while ((msg[i] = strtok(msg[i], " ")) && ++i);
//将字符串类型转成int型
char* op = msg[0];
int num1 = atoi(msg[1]);
int num2 = atoi(msg[2]);
if (strcasecmp(op, "add") == 0) {
//对比字符串是否相等,忽略大小写
cout << num1 + num2 << endl;
}
从十进制整数转成十六进制整数
#include <iostream>
#include <string>
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) {
string res = "";
char hex[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; //记录十六进制所需的字符
while(n > 0){ //连除16取余
res = hex[n % 16] + res; //每次加在字符串首
n /= 16;
}
return res;
}
#include <string>
#include<algorithm>
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 ans;
while(n)
{
int m = n%16;
if(m<10)
ans.push_back(char('0'+m));
else
ans.push_back(char('A' + m-10));
n/=16;
}
reverse(ans.begin(), ans.end());//反转字符串
return ans;
}