C++ 小结
搭搭积木还是会的。
string
字符串替换
#include <regex>
std::string string("hello $name");
string = std::regex_replace(string, std::regex("\\$name"), "Somename");
字符串分割
vector<string> str_split(const string& str, const string& delim)
{
vector<string> tokens;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == string::npos) pos = str.length();
string token = str.substr(prev, pos-prev);
if (!token.empty()) tokens.push_back(token);
prev = pos + delim.length();
}
while (pos < str.length() && prev < str.length());
return tokens;
}
字符串拼接
date
http://www.cplusplus.com/reference/ctime/strftime/
date to string
std::string
current_time ()
{
time_t now = time (NULL);
struct tm tstruct;
char buf[40];
tstruct = *localtime (&now);
strftime (buf, sizeof (buf), "%Y-%m-%d %H:%M:%S", &tstruct);
return buf;
}
#include <iostream>
#include <iomanip>
#include <ctime>
int main()
{
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::cout << std::put_time(&tm, "%d-%m-%Y %H-%M-%S") << std::endl;
}
#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>
int main()
{
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::ostringstream oss;
oss << std::put_time(&tm, "%d-%m-%Y %H-%M-%S");
auto str = oss.str();
std::cout << str << std::endl;
}
spdlog
auto my_logger = spdlog::basic_logger_mt("basic_logger", "basic.txt");
unordered_map
key 存在性
m.find(key) == m.end()
vector
slice
v2 = std::vector<int>(v1.begin() + 1, v1.end());
字节对齐
struct
{
char a;
} s;
| 1 |
size = 1
struct
{
char a;
int b;
} s;
| 1 | | | | 4 | x | x | x |
size = 8
struct
{
char a;
int b;
char c;
} s;
| 1 | | | | 4 | x | x | x | 1 | | | |
size = 12
struct
{
char a;
int b;
double c;
} s;
| 1 | | | | 4 | x | x | x | 8 | x | x | x | x | x | x | x |
size = 16