常用语句 - C++
跳到导航
跳到搜索
赋值
map
unordered_map<string, int> um1 = {{"apple", 1}, {"banana", 2}, {"orange", 3}}; // map 相同
结构体
struct RES { int type; // 0=exit, 1=ok string val; // value }; RES res1; res1 = {1, "ok"};
转换
数值转为字符串
#include <string> str1 = to_string(num1);
字符串转换成整数
#include <string> num1 = stoi(str1);
条件
map 元素是否存在
#include <map> map<string, int> map1; map1["key1"] = 123; if (map1.count("key1")) { ... }
循环
map
# C++11 for (const auto& pair1 : map1) { cout << pair1.first << ": " << pair1.second << endl; } # 基本方法:迭代器 for (map<int, string>::iterator it = map1.begin(); it != map1.end(); ++it) { cout << it->first << ": " << it->second << endl; } # 函数封装 #include <algorithm> void printPair(const pair<int, string>& p) { cout << p.first << ": " << p.second << endl; } ... for_each(map1.begin(), map1.end(), printPair);
Compile
当前函数名
在大多数编译器中,__FUNCTION__ 宏会被替换为当前函数名
cout << "Current Function: " << __FUNCTION__ << endl;
- __FUNCTION__ : myfun
- __func__ : myfun
- __PRETTY_FUNCTION__ : void sys_info(string), gcc