What is the complexity of std::string::substr member function?

前端 未结 3 757
悲&欢浪女
悲&欢浪女 2020-12-18 07:37

What is the complexity of std::string::substr member function? Is it defined by standard or implementation-defined?

相关标签:
3条回答
  • 2020-12-18 07:42

    A naïve implementation would be O(k) where k is the length of the resulting substring. std::string does not support copy-on-write. If you want O(1) substring operations, use a data structure such as a Rope.

    0 讨论(0)
  • 2020-12-18 07:43

    This is all that standard has to say about it:

    n3242, 21.4.7.8

    1. Requires: pos <= size()
    2. Throws: out_of_range if pos > size()
    3. Effects: Determines the effective length rlen of the string to copy as the smaller of n and size() - pos
    4. Returns: basic_string<charT,traits,Allocator>(data()+pos,rlen).

    So the answer would be no, the complexity is not defined.

    EDIT: Corrected as per n3242, pos > size not pos >= size

    0 讨论(0)
  • 2020-12-18 07:45

    The C++11 standard does not define the performance characteristics of substr, either in 21.4.7.8 or anywhere else I could find. In practice you can almost certainly expect O(n) performance with n being the length of the result.

    0 讨论(0)
提交回复
热议问题