C++ 常用小技巧
1.使用{}初始化,不能用于stack和queue
pair<int, int> p;
vector<int> v;
p = make_pair(3, 4);
v.push_back(4); v.push_back(5);
//while you can just do this:
p = {3, 4};
v = {4, 5};
//even a more complex pair
pair<int, pair<char, long long> > p;
p = {3, {'a', 8ll}};
//What about vector, deque, set and other containers?
// vector deque set 可以同样使用
vector<int> v;
v = {1, 2, 5, 2};
for (auto i: v)
cout << i << ' ';
cout << '\n';
// prints "1 2 5 2"
deque<vector<pair<int, int>>> d;
d = {{{3, 4}, {5, 6}}, {{1, 2}, {3, 4}}};
for (auto i: d) {
for (auto j: i)
cout << j.first << ' ' << j.second << '\n';
cout << "-\n";
}
// prints "3 4
// 5 6
// -
// 1 2
// 3 4
// -"
set<int> s;
s = {4, 6, 2, 7, 4};
cout << get<2>(t) << '\n';
2.不常用的函数
最大公约数
__gcd(value1, value2)
__gcd(18, 27) = 9.
统计二进制表示中从第一个1在第几位(从地位开始计算,小标为1)
__builtin_ffs(x)
__builtin_ffs(10) = 2; //10的而二进制是10
__builtin_ffs(3) = 1;
返回转化为unsigned long long的二进制数中前导0的个数
_builtin_clz(x)
__builtin_clz(16) = 27 because 16 is ' ... 10000'. //所以返回 32 — 5 = 27.
返回转化为unsigned int的二进制数中末尾连续0的个数
__builtin_ctz(x)
e.g. __builtin_ctz(16) = 4
because 16 is '...1 0000 '. Number of trailing 0-bits is 4.
返回二进制1的个数
__builtin_popcount(x)
e.g. __builtin_popcount(14) = 3 because 14 is '... 111 0' and has three 1-bits.
3. C++0x Strings
one) Raw Strings (From IvayloS’s comment)
You can have UTF-8 strings, Raw strings and more. Here I want to show raw strings. We define a raw string as below:
string s = R"(Hello, World!)"; // Stored: "Hello, World!"
A raw string skips all escape characters like \n or \". e.g.
string str = "Hello\tWorld\n";
string r_str = R"(Hello\tWorld\n)";
cout << str << r_str;
Output:
Hello World
Hello\tWorld\n
C++ 处理字符串 切片
stringstream ssin(sentence);
vector<string> strs;
string str;
while (ssin >> str) strs.push_back(str);
转自:http://codeforces.com/blog/entry/15643