2

Minimal Reproducible example:

using namespace std;

#include<string>
#include<string_view>
#include<iostream>

int main()
{
    string s = "someString";
    string_view sV = string_view(s);
    string_view sVTwo = string_view(begin(s), end(s));
    return 0;
}

Is the time complexity of creating the string_view sV linear relative to the number of chars in the string s or is it irrelevant how long the string s is? Likewise, is the time complexity of the construction of sVTwo linear or constant depending on how many chars are in the string?

The reason I am confused is I cannot tell which of these constructors here: https://en.cppreference.com/w/cpp/string/basic_string_view/basic_string_view is being used to construct the string.

3
  • Doesn't the link state that the complexity is constant? A std::string knows its own length since it has a const size() function. It's when a raw char * is used where the length of the string comes into play, since a character pointer knows nothing about the length of the string, and must iterate until a null is reached. Commented Oct 17, 2021 at 3:19
  • 1
    It's not using any of the string_view constructors. It's using the "string to string_view" conversion operator. Commented Oct 17, 2021 at 3:19
  • 1
    Protip: never put using namespace std; above #include directives, and ideally never use using namespace, instead import specific type-names. Commented Oct 17, 2021 at 3:19

1 Answer 1

8

Is the time complexity of creating the string_view sV linear relative to the number of chars in the string s or is it irrelevant how long the string s is?

string_view(s) will call the string's operator std::string_view(), which is equivalent to return string_view(data(), size()), and since string's data() and size() are both O(1), so the complexity has nothing to do with the length of the string.

Likewise, is the time complexity of the construction of sVTwo linear or constant depending on how many chars are in the string?

It will call string_view(It first, End last) and use std::to_address(first) and last - first to initialize the string_view's member variables. Since the former and pointer arithmetic are both constant time, this is also constant time. Please note that this function was introduced in C++20, and calling string_view(begin(s), end(s)) in C++17 is ill-formed.

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

Comments

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.