Is std::string a container class in standard c++ library, restricted to hold only char elements?
It's a typedef of std::basic_string<char>
, actually. std::basic_string
is a container class specifically designed for string operations. This container can be used for wide characters (wchar_t
) as well; for that case its typedef would be wstring
.
std::string is a basic_string. It's not necessarily a char, but it has to follow the char traits http://www.cplusplus.com/reference/string/char%5Ftraits/
std::string as a typedef for basic_string<char, std::char_traits<char>, std::allocator<char> >
is pretty much limited to the char type.
However, I don't think basic_string itself is necessarily limited to only character types (though, as the name suggests, it might be intended to be used for string data).
#include <string>
#include <cassert>
int main()
{
std::basic_string<int> numbers_1, numbers_2;
numbers_1 += 1;
numbers_2 += 2;
std::basic_string<int> numbers_3 = numbers_1 + numbers_2 + 3;
unsigned pos = numbers_3.find(10);
assert(pos == std::basic_string<int>::npos);
}
A std::basic_string<>
is a class that is very much like a sequence container. Note that std::basic_string
can contain any POD type, not just elements of type char
(which is what a std::string
is) or wchar_t
(std::wstring
).
I believe that a basic_string
supports all the operations of a sequence container. However, note that by definition a container type can hold any assignable and copy-constructable types - not just POD types. So a basic_string
is very much like a container, but strictly speaking it's not a container.
In other words there are types that can be used with a container that cannot be used with a basic_string
. But for those types that can be used with a basic_string
, the std::basic_string
provides the full interface of a sequence container (I think) plus additional functionality.