如何用C++17标准库替代boost::is_any_of()和boost::split()?
C++17替代boost::split与boost::is_any_of("/")的实现方案
直接用C++17标准库实现一个等效的split函数即可,不需要依赖Boost。下面是和你原代码行为完全一致的实现:
#include <string> #include <vector> // 复刻boost::split默认行为的分割函数 void split(std::vector<std::string>& result, const std::string& input, char delimiter) { size_t start = 0; size_t end = input.find(delimiter); while (end != std::string::npos) { result.push_back(input.substr(start, end - start)); start = end + 1; end = input.find(delimiter, start); } // 处理最后一段内容 result.push_back(input.substr(start)); } // 调用示例,和你原代码逻辑对齐 int main() { std::string material = "metal/plastic//glass"; std::vector<std::string> materialVector; split(materialVector, material, '/'); // 此时materialVector内容为 ["metal", "plastic", "", "glass"],和boost版本输出一致 return 0; }
额外说明
- 这个实现保留了
boost::split的默认规则:连续分隔符(比如//)会生成空字符串元素,不会忽略首尾的空内容 - 如果需要过滤空元素,只需在
push_back前加判断:if (start != end) result.push_back(...),同时最后一段为空时也可以跳过 - 若后续需要支持多字符分隔符(对应
boost::is_any_of的多参数场景),可以修改函数参数为const std::string& delimiters,遍历查找所有分隔符即可,单字符场景下上面的实现效率更高
内容的提问来源于stack exchange,提问作者cvaqabond
相关产品推荐
相关产品推荐

