将std::string就地标记为键值映射

In place Tokenization of std::string into a map of Key Value

本文关键字:记为 键值 映射 std string      更新时间:2023-10-16

在C语言中,分隔符可以用null替换,并且可以使用带有比较函数的char* -> char*映射。

我正试图找出最快的方法在现代c++中做到这一点。这样做是为了避免在地图中复制字符。

std::string sample_string("name=alpha;title=something;job=nothing");

std::map<std::string,std::string> sample_map;

不复制字符

可以丢失原始输入字符串

两个std::字符串不能指向相同的底层字节,所以不可能使用字符串。

要避免复制字节,可以使用迭代器:

struct Slice {
  string::iterator begin, end;
  bool operator < (const& Slice that) const {
    return lexicographical_compare(begin, end, that.begin, that.end);
  }
};
std::map<Slice,Slice> sample_map;

并且要注意,如果修改了原始字符串,所有的迭代器都将无效。