简体   繁体   English

C ++时空复杂的字符串类擦除成员函数

[英]C++ Time and Space Complexity of string class erase member function

I wanted to know if someone knew the implementation of the C++ string::erase function and it's complexity. 我想知道是否有人知道C ++ string :: erase函数的实现及其复杂性。 I know the C++ string is an object of characters. 我知道C ++字符串是一个字符对象。 I'm assuming it doesn't allocate and create a new object of characters and then copy over the characters from the old string O(n) and O(n) space. 我假设它没有分配和创建一个新的字符对象,然后复制旧字符串O(n)和O(n)空间中的字符。 Does it shift over the characters O(n) and O(1) space? 它是否会移动字符O(n)和O(1)空间? I've looked on cplusplus.com and Bjarne Stroustrup book but haven't been able to find the answer. 我查看了cplusplus.com和Bjarne Stroustrup的书,但未能找到答案。 Can someone point me to the source code where it's implemented or know the answer? 有人能指出我实施的源代码或知道答案吗?

Thanks! 谢谢!

As stated in the comments , the standard doesn't specify any complexity requirements for many basic_string functions (including erase ). 评论中所述 ,该标准未指定许多basic_string函数(包括erase )的任何复杂性要求。 This is partly because there have historically been a number of different implementation strategies (most famously, copy-on-write was popular in the C++98 era), so the committee was reluctant to specify anything too precisely. 这部分是因为历史上有许多不同的实施策略(最着名的是,写作时复制在C ++ 98时代很流行),因此委员会不愿意过于精确地指定任何内容。

The basic behavior of typical, modern implementations is very much like vector<char> : insertion and deletion are cheap at the end (with amortized reallocations) and expensive at the beginning. 典型的现代实现的基本行为非常类似于vector<char> :插入和删除在最后是便宜的(具有分期重新分配)并且在开始时是昂贵的。 Small strings are handled without memory allocation at all (by reusing the pointers' space to store the characters). 处理小字符串时根本没有内存分配(通过重用指针的空间来存储字符)。 This means that erasure can result in copying the whole string if it becomes very short (but then the copy is cheap). 这意味着擦除可能会导致复制整个字符串,如果它变得非常短(但副本很便宜)。 It also means that iterators and references are invalidated more easily than with vector . 它还意味着迭代器和引用比使用vector更容易失效

There aren't any algorithms that perform better on a string , but there are alternate data structures that have different performance characteristics. 没有任何算法string上表现更好,但是存在具有不同性能特征的备用数据结构 The rope is typical among these in that it provides somewhat slower access but much faster insertion and deletion. 绳索在这些中是典型的,因为它提供了稍慢的访问但更快的插入和删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM