位运算交换数字
// cpp-style (recommanded)
void mySwap(int &p, int &q)
{
q = p^q;
p = q^p;
q = q^p;
cout << "p=" << p << "q=" << q << endl;
}
int a = 2, b = 3;
swap(a,b);
Arr/Str
#include <bits/stdc++.h>
using namespace std;
char a[100]; // 99 chars max (end with '\0')
string b;
// string b[100] also; normally b[MAXL] in oi.
int main()
{
// a for c-style, b for cpp-style
gets(a); // end with \n or EOF
getline(cin,b); // end with one before \n
puts(a);
cout << b;
int la = strlen(a); // O(n)
int lb = b.size(); // O(1) or b.length();
/* c++11 useful funcs
stoi();
stoll();
stold();
to_string();*/
string::iterator it = b.begin(); // iterator *pin*
while(it!=b.end())
{
putchar(*it); it++;
}
return 0;
}
I/O
不建议混用cin/cout
和printf/scanf
加速cin/cout:
// even faster than scanf/printf
std::ios::sync_with_stdio(false);
// c-style string disabled
std::cin.tie(0);
std::cout.tie(0);
// can't use <cstdio> anymore
读入优化:
#include <bits/stdc++.h>
using namespace std;
void s(int &p)
{
scanf("%d", &p);
}
void c(int &p)
{
cin >> p;
}
void Read(int &p)
{
p = 0;
char c = getchar();
while(!isdigit(c))
c = getchar();
while(isdigit(c))
p = p*10 + (c-'0'), c = getchar();
}
double t1, t2, ta1, ta2, ta3, ta4;
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
freopen("test.txt", "r", stdin);
int p;
t1 = clock();
for(int i=1; i<900000; i++) c(p);
t2 = clock();
ta1 = clock();
for(int i=1; i<900000; i++) s(p);
ta2 = clock();
ta3 = clock();
for(int i=1; i<900000; i++) Read(p);
ta4 = clock();
printf("cin:%.21fs\n", (t2-t1)/1000);
printf("scanf:%.21fs\n", (ta2-ta1)/1000);
printf("Read:%.21fs\n", (ta4-ta3)/1000);
return 0;
}
结构体
#include <bits/stdc++.h>
using namespace std;
// c-style structure
// struct point {int x; int y;};
// cpp-style structure
struct point
{
int x; int y;
point(int x=0, int y=0) : x(x), y(y){};
// also point(int x, int y) {this->x=x; this->y=y;}
};
ostream &operator << (ostream &output, point &p)
{
output << "(" << p.x << "," << p.y << ")";
return output;
}
point operator + (point A, point B)
{
return point(A.x+B.x, A.y+B.y);
}
int main()
{
point a(1,2), b(3,4), c;
c = a+b;
cout << a << ' ' << b << ' ' << c << '\n';
return 0;
}
#include <bits/stdc++.h>
using namespace std;
// c-style structure
// struct point {int x; int y;};
// cpp-style structure
struct point
{
int x; int y;
point(int x=0, int y=0) : x(x), y(y){};
// also point(int x=0, int y=0) {this->x=x; this->y=y;}
};
ostream &operator << (ostream &output, point &p)
{
output << "(" << p.x << "," << p.y << ")";
return output;
}
istream &operator >> (istream &input, point &p)
{
input >> p.x >> p.y;
return input;
}
point operator + (point A, point B)
{
return point(A.x+B.x, A.y+B.y);
}
bool cmp(point a, point b)
{
if(a.x==b.x) return a.y<b.y;
else return a.x<b.x;
}
int main()
{
int i=3;
point a[i];
for(int j=0; j<i; j++)
{
cin >> a[j];
}
sort(a, a+i, cmp);
for(int j=0; j<i; j++)
{
cout << a[j] << ' ';
}
cout << '\n';
return 0;
}