如何返回std :: string的常量视图?

Joã*_*res 2 c++ string string-view

在使用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]);
    }
};
Run Code Online (Sandbox Code Playgroud)

Tra*_*kel 5

听起来像是std::string_view您的课程!如果您没有C ++ 17支持,请尝试std::experimental::string_view。如果不可用,请尝试boost::string_view。所有这些选择都可以以相同的方式使用(只需替换std::string_view为您使用的任何方式):

std::string_view operator [](size_t const i) const {
    return std::string_view(&data[i], 1);
}
Run Code Online (Sandbox Code Playgroud)

欢迎使用C ++,这里总是有另一个厨房水槽!