cong
cong

Reputation: 1187

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

In 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?

Upvotes: 2

Views: 682

Answers (3)

HDJEMAI
HDJEMAI

Reputation: 9800

std::string is defined in header <string> as a template like this:

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.

They are implemented differently.

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477040

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. This shows further differences: basic_string may only be specialized for literal types. And basic_string also takes a third parameter, the traits, which determine how comparison is done.

What strings have in common with vectors is that they store the data contiguously.

Upvotes: 7

Jesper Juhl
Jesper Juhl

Reputation: 31465

std::string is not a std::vector. It's a std::basic_string.

Upvotes: 4

Related Questions