C++ std::string 是一个容器吗?

2022-01-24 00:00:00 containers c++ stdstring

对于你们中的一些人来说,这可能是一个简单的问题.但我想知道 std::string 是否是一个容器.容器是指容器,例如 std::vectorstd::liststd::deque.

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.

由于 std::basic_string<> 接受整数字符以外的其他类型,但也正在通过使用字符数组进行优化.我不清楚它属于哪个类别.

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.

这将编译:

#include <string>
#include <iostream>

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

但是通过添加这一行:

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

不会的.因此,根据这些事实,我可以得出结论,std::basic_string 不适用于字符以外的其他类型.

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.

推荐答案

是的,std::basic_string 模板满足 Container 概念的所有要求.但是,我认为它对包含类型有更高的要求.只是想弄清楚到底是什么.

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.

(这不是 Bjarne 的概念.只是标有23.2.1 通用容器要求"的标准部分.)

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

相关文章