← 返回首页

实用代码片段

字符串分割(std::string delimiter)

vector<string> split(string s, string delimiter) {
    size_t pos_start = 0, pos_end, delim_len = delimiter.length();
    string token;
    vector<string> res;

    while ((pos_end = s.find(delimiter, pos_start)) != string::npos) {
        token = s.substr(pos_start, pos_end - pos_start);
        pos_start = pos_end + delim_len;
        res.push_back(token);
    }

    res.push_back(s.substr(pos_start));
    return res;
}

字符串分割(char delimiter)

#include <iostream>
#include <string>

vector<string> split(const string &s, char delim) {
    vector<string> result;
    stringstream ss(s);
    string item;

    while (getline(ss, item, delim)) {
        if (!item.empty()) {
            result.push_back(item);
        }
    }
    return result;
}

for_each 遍历修改

#include <algorithm>

std::for_each(nums.begin(), nums.end(), [](int &n){ n++; });

Map 转 Vector

using namespace std;

vector<int> keys;

transform(begin(map_in), end(map_in), back_inserter(keys),
    [](decltype(map_in)::value_type const& pair) {
        return pair.first;
    });