c++ - 将 std::string 转换为 std::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)) 格式错误。

https://stackoverflow.com/questions/69601008/

相关文章:

azure-devops - Azure Devops yml 管道 if else 条件变量

haskell - 为什么我的 ByteString 在我的 x86_64 架构上是 BigEndi

arrays - 为什么我在执行 strcat() 时得到错误的源字符串输出?

kotlin - 获取列表 kotlin 范围之间的项目

haskell - 如何使组合数据构造函数成为类的实例?

python - 为什么在为 python 安装 psutil 包时会出现错误?

c# - GraphQL : Not Getting EF Related objects afte

android - 您上传的文件不是格式正确的 zip 存档

c# - 从 Swagger (Swashbuckle) 隐藏参数

javascript - 使用 reduce,从一个对象数组中,在对象的数组属性中创建一组元素