C++ 一些小技巧
部分内容来自网上~
头文件:
/*
Problem:
Status :
By WF,
*/
#include "algorithm"
#include "iostream"
#include "cstring"
#include "cstdio"
#include "string"
#include "stack"
#include "cmath"
#include "queue"
#include "set"
#include "map"
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=1e6+5;
//从右开始顺时针
int dir4[4][2]={0,1,1,0,0,-1,-1,0};
int dir8[8][2]={0,1,1,1,1,0,1,-1,0,-1,-1,-1,-1,0,-1,1};
int main()
{
//freopen("in.txt","r",stdin);
return 0;
}
输入输出:
printf输出float和double都可以用%f,double还可以用%lf。
scanf输入float用%lf,double输入用%lf,不能混用。
long long 用%lld。
printf("%d\n",i>>1 );
printf("%10.2f\n",d );//右对齐,占10位字符,保留2位小数。
printf("%-10.2f\n",d );//左对齐,占10位字符,保留2位小数。
printf("%s\n",s );//输出字符串
fprintf(stderr, "%s\n", );//输出到文件
sprintf(s,"%d%d",a,b);//输出到字符串s中
sscanf(s,"%d:%d:%d",&h,&m,&s)//从s(例如s=“12:59:59”)中读取h,m,s。
读取一行(包括空格)(注意使用前别忘了用getchar()吸收回车符):
fgets(s,sizeof s,stdin);
gets(s);//有缓冲区溢出危险
自定义STL优先队列的优先级:
//定义结构,使用运算符重载,自定义优先级1
struct cmp1{
bool operator ()(int &a,int &b){
return a>b;//最小值优先
}
};
struct cmp2{
bool operator ()(int &a,int &b){
return a<b;//最大值优先
}
};
//定义结构,使用运算符重载,自定义优先级2
struct number1{
int x;
bool operator < (const number1 &a) const {
return x>a.x;//最小值优先
}
};
struct number2{
int x;
bool operator < (const number2 &a) const {
return x<a.x;//最大值优先
}
};
priority_queue<int>que;//采用默认优先级构造队列。最大值优先
priority_queue<int,vector<int>,cmp1>que1;//最小值优先
priority_queue<int,vector<int>,cmp2>que2;//最大值优先
priority_queue<int,vector<int>,greater<int> >que3;//最小值优先。注意“> >”的空格。
priority_queue<int,vector<int>,less<int> >que4;//最大值优先
priority_queue<number1>que5;
priority_queue<number2>que6;
string流的用法(以Hdu 2072为例):
//题目大意:输入一行英文句子,输出共有多少不同的单词。
#include <sstream>
set<string>s;
string row,word;
while(getline(cin,row) && row!="#" ){
s.clear();
stringstream str_cin(row);
while(str_cin>>word){
s.insert(word);
}
cout<<s.size()<<endl;
}
lower_bound & upper_bound:

C/C++ char数组的相关操作:
char str[100] = "Hello,my name is Bruce."; char substr[100] = "my"; char str2[100] = "I am Tom"; char ch = ','; int n = 4; //1.字符串长度: int len = strlen(str); //2.字符串比较(相同返回0): int ret1 = strcmp(str,str2); int ret2 = strncmp(str,str2,n); //比较str和str2的前n个字符 //3.查找 char *p1 = strchr(str,ch); //返回值为指针,找不到返回null char *p2 = strstr(str,substr); cout<< p1 <<endl; //结果为:",my name is Bruce." cout<< *p1 <<endl; //结果为:"," cout<< p1-str <<endl; //结果为:"5" //4.附加: strcat(str,str2); //把str2连接到str后面 strncat(str,str2,n); //把str2的前n个字符连接到str后面 //5.替换 strcpy(str,str2); //用str2替换str strncpy(str,str2,n); //用str2的前n个字符替换str的前n个字符
合并数组中相同的项:
int a[10] = { 1,2,2,3,4,5,5,5,5,6};
int nCount=unique(a,a+10)-a;//合并掉相同的项
for(int i=0;i<nCount;++i)
{
cout<<a[i]<<" ";//结果为:1 2 3 4 5 6
}

浙公网安备 33010602011771号