Is std::string a container class in standard c++ library, restricted to hold only char elements?
4 Answers
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.
4 Comments
basic_string<> cannot hold non-POD types which a container like vector<> could hold. But for POD types (like a plain-old struct) you can have a std::basic_string<mystruct_t>. To be honest, I'm just going by what the standard says - it looks like after a bit of experimentation, some compilers (GCC 3.4.5 and Comeau) will accept at least simple non-POD types as a type used for basic_string<> and some compilers won't accept a simple aggregate POD type (Digital Mars, VC6). VC9 behaves as the standard seems to call for.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); } Comments
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_traits/
1 Comment
std::string is a std::basic_string<char, std::char_traits<char>, std::allocator<char> >, which is absolutely restricted to char.