C++ Is a std::string a container?

2020-04-03 21:03发布

问题:

This might be a simple question for some of you. But I was wondering if a std::string is a container. By container I mean the containers like for example std::vector, std::list and std::deque.

Since std::basic_string<> accepts other types than integral characters, but also is being optimized by working with character arrays. It isn't really clear to me in which category it falls.

This will compile:

#include <string>
#include <iostream>

int main() {
    std::basic_string<int> int_str;
    int_str.push_back(14);
    return 0;
}

But by adding this line:

std::cout << int_str << std::endl;

It won't. So by these facts I could conclude that an std::basic_string was not intended to work with other types than characters.

It might be a strange question for you. The reason I need to know this is because I'm working on a framework and I'm still not able to determine in which category a "string" would fall.

回答1:

Yes, the std::basic_string template fulfills all the requirements of the Container concept. However, I think it has stronger requirements on the contained type. Just trying to dig out exactly what.

(This is not Bjarne's Concepts. Just the bit of The Standard labeled "23.2.1 General container requirements".)



回答2:

According to standards(2003,2011) std::basic_string is a container only for POD types. I.e. fundamental types or plain structs/classes without constructors, destructors or virtual functions. But gnu stdlib allow use non-POD types with std::basic_string. Here is an example of working with basic_string and non-POD types.

And if you what to make your example works you should define operator

std::ostream& operator<<(::std::ostream& out, std::basic_string<int> &dat) 
{ 
    out << dat[0];
    return out; 
}

Or something like that.



回答3:

Well it is safe to say it is not a container at least not in the normal way you would think of an std container.

Most simple example is that you cant put any thing you want in it.

But it does have some classification of a container like the fact that you can put some of the basic types into it even if they are not chars, and perhaps most amazing thing is that you can get an iterator to it as if it was a normal container.

So is it a containr? I would say yes but! it is not an all genery one.