c++ - 将 std::string 转换为 std::string_view 的时间复杂度

标签 c++ string string-view

最小可重现示例:

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

创建 string_view sV 的时间复杂度是否与字符串 s 中的字符数成线性关系,还是与字符串 s 的长度无关?同样,构造 sVTwo 的时间复杂度是线性的还是常量取决于字符串中有多少个字符?

我感到困惑的原因是我在这里无法分辨这些构造函数中的哪一个:https://en.cppreference.com/w/cpp/string/basic_string_view/basic_string_view用于构造字符串。

最佳答案

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) 将调用 stringoperator std::string_view() ,这相当于 return string_view(data(), size()),因为 stringdata() size()都是O(1),所以复杂度与字符串的长度无关。

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

它将调用 string_view(It first, End last) 并使用 std::to_address(first)last - first 来初始化string_view 的成员变量。由于前者和指针运算都是常数时间,所以这也是常数时间。请注意,此函数是在 C++20 中引入的,在 C++17 中调用 string_view(begin(s), end(s)) 格式错误。

关于c++ - 将 std::string 转换为 std::string_view 的时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69601008/

相关文章:

javascript - 如何从odd数组中获取字符串?

c++ - 扩展string_view是未定义的行为吗?

c++ - 如何从核心文件中获取有关崩溃的信息?

c++ - 如何在 qt5 上绘制 QDialog 的插入符号/箭头底部

c++ - 如何将 "tighten up"参数传递给模板化函数?

java - 如何在java中查找字符串中整个单词的索引

java - 包含阿拉伯和西方字符的字符串连接

c++ - 是否有其他容器类型的 string_view 等效项?

c++ - 解析文件时,我可以将 std::string_view 与 getline 一起使用吗?

c++ - 语义 Action 后丢弃解析结果