3

在 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]);
    }
};
4

1 回答 1

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);
}

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

于 2017-01-17T00:34:48.577 回答