【发布时间】:2017-01-17 00:26:36
【问题描述】:
在使用 C++ 进行原型设计和玩耍时,尝试一些概念来制作可识别 utf8 的不可变字符串,但我遇到了以下两难境地:
有什么方法可以返回一个字符串的不可变视图。就像,我希望能够返回一个引用原始字符串一部分的子字符串,而不是返回一个子字符串。
// Just some quick prototyping of ideas.
// Heavier than just a normal string.
// Construction would be heavier too because of the indices vector.
// Size would end up being O1 though.
// Indexing would also be faster.
struct ustring {
std::string data;
std::vector<size_t> indices;
// How do I return a view to a string?
std::string operator [](size_t const i) const {
return data.substr(indices[i], indices[i + 1] - indices[i]);
}
};
【问题讨论】:
-
你有 c++17 中的
string_view类吗? -
另外,一些库在 c++14 中实现了
<experimental/string_view>,在此之前,boost 有一个 string_view 库。您也可以使用 GSL。
标签: c++ string string-view