【问题标题】:How to return a constant view of a std::string?如何返回 std::string 的常量视图?
【发布时间】: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 中实现了&lt;experimental/string_view&gt;,在此之前,boost 有一个 string_view 库。您也可以使用 GSL。

标签: c++ string string-view


【解决方案1】:

听起来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++,总有另一个厨房水槽!

【讨论】:

  • 在 Visual Studio 2017 中,标题确实出现在智能感知中,但是,当我执行 std:: 时,没有 string_viewexperimental::string_view 可用。也许他们只是保留了这个词以备将来使用?
  • 您是#include &lt;string_view&gt; 还是#include &lt;experimental/string_view&gt;
  • #include
  • #include 或尝试使用std::string_view 时编译是否失败? (我在这里掌握了一点——我并没有真正使用 Visual Studio 或 MSVC)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
  • 1970-01-01
  • 2020-02-17
  • 2011-03-03
  • 2021-06-30
相关资源
最近更新 更多