简体   繁体   English

不是std :: string std :: vector <char> ?

[英]Isn't a std::string a std::vector<char>?

In c++ primer 5th, 9.2.5. 在C ++ Primer 5th,9.2.5中。 Assignment and swap, I read about this: 分配和交换,我读到以下内容:

The fact that elements are not moved means that, with the exception of string, iterators, references, and pointers into the containers are not invalidated. 不移动元素的事实意味着,除了字符串之外,迭代器,引用和指向容器的指针都不会失效。 They refer to the same elements as they did before the swap. 它们所引用的元素与交换之前相同。

So, why is string a exception? 那么,为什么字符串是一个例外? I always think that string is a vector, isn't that true? 我一直认为字符串是向量,不是吗?

The very wording you cite demonstrates that strings aren't vectors. 您引用的措辞恰恰证明了字符串不是向量。 When you swap two vectors, iterators remain valid and point into the new vectors. 交换两个向量时,迭代器保持有效并指向新向量。 There is no analogous requirement on strings. 对字符串没有类似的要求。 This allows strings to use small-buffer optimizations. 这允许字符串使用小缓冲区优化。

It may be more appropriate to compare basic_string and vector , because those are both templates that are parametrized on element type and allocator. 比较basic_stringvector可能更合适,因为它们都是在元素类型和分配器上参数化的模板。 This shows further differences: basic_string may only be specialized for literal types. 这显示了进一步的差异: basic_string只能专用于文字类型。 And basic_string also takes a third parameter, the traits, which determine how comparison is done. basic_string还带有第三个参数traits,它确定比较的完成方式。

What strings have in common with vectors is that they store the data contiguously. 字符串与向量的共同点是它们连续存储数据。

std::string is not a std::vector . std::string 不是 std::vector It's a std::basic_string . 这是一个std :: basic_string

std::string is defined in header <string> as a template like this: std::string在标头<string>定义为如下模板:

template< 
    class CharT, 
    class Traits = std::char_traits<CharT>, 
    class Allocator = std::allocator<CharT>
> class basic_string;

But vector is defined differently: 但是向量的定义不同:

template<
    class T,
    class Allocator = std::allocator<T>
> class vector;

So std::string and vector<char> are not the same. 因此std::stringvector<char>不相同。

They are implemented differently. 它们的实现方式有所不同。

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

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