3

While prototyping and playing around in C++, trying some concepts for making a utf8-aware immutable string, I stood with the following dilemma:

Is there any way to return a immutable view of a string. Like, instead of returning a substring, I want to be able to return a substring that references a part of the original string.

// 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]);
    }
};
2
  • 3
    Do you have the string_view class available to you from c++17? Commented Jan 17, 2017 at 0:29
  • 3
    alternately, some libraries implemented <experimental/string_view> in c++14, and before that, boost had a string_view library. You could also use the GSL. Commented Jan 17, 2017 at 0:34

1 Answer 1

5

Sounds like std::string_view is the class for you! If you don't have C++17 support, then try out std::experimental::string_view. If that's not available, try out boost::string_view. All of those choices can be used in the same way (just replace std::string_view with whatever you use):

std::string_view operator [](size_t const i) const {
    return std::string_view(&data[i], 1);
}

Welcome to C++, where there's always another kitchen sink!

Sign up to request clarification or add additional context in comments.

7 Comments

In Visual Studio 2017 the header does appear in the intellisense, however, when I do std:: there's no string_view nor experimental::string_view available. Maybe they just reserved the word for future use?
Did you #include <string_view> or #include <experimental/string_view>?
#include <string_view>
Does compilation fail at the #include or at the attempt to use std::string_view? (I'm grasping a bit here -- I don't really use Visual Studio or MSVC)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.