c++ - STL - 字符串是 vector 吗?

标签 c++ string vector stl

我在一些测验中遇到了一个问题 “ Is a string a vector? If yes, in what way? If no, why not? ” 他们都可以随机访问内容。 但是 string 有一些 vector dosn`t 的方法。它也可能有 reference count 。 所以很明显字符串不完全是一个 vector (typedef string vector) 是否有已知的实现 class string : public vector <char> ? 如果不是 - 不实现的原因是什么?

最佳答案

从纯粹的哲学角度来看:是的,字符串是 vector 的一种类型。它是存储字符的连续内存块( vector 是存储任意类型对象的连续内存块)。因此,从这个角度来看,字符串是一种特殊的 vector 。

在设计和实现方面std::stringstd::vector ,它们共享一些相同的界面元素(例如连续的内存块,operator[]),但是std::string 源自std::vector (旁注:您不应该公开派生自标准容器,因为它们不是设计为基于类的——例如,它们没有虚拟析构函数),它们也不能直接相互转换。也就是说,以下将不会编译:

std::string s = "abc";
std::vector<char> v = s; // ERROR!

但是,由于它们都支持迭代器,因此您可以将字符串转换为 vector :

std::string s = "abc";
std::vector<char> v(s.begin(), s.end()); // note that the vector will NOT include the '\0' character

std::string将不再有引用计数(从 C++11 开始),因为许多实现使用的写时复制功能被 C++11 标准禁止。

从内存的角度来看,std::string 的实例看起来非常类似 std::vector<char> (例如,它们都有指向其内存位置、大小、容量的指针),但两个类的功能不同。

关于c++ - STL - 字符串是 vector 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19730488/

相关文章:

java - 我不可能理解所描述的字符串搜索方法。什么是 uFFFF?

c++ - 访问指针 vector 中的信息

c++ - 在 2dim vector 中插入一个值?

c++ - 运行时错误 : reference binding to null pointer of type 'std::vector<int, std::allocator<int>>' (STL_vector. h)

c++ - 模板元编程积分特化

c++ - 将变量传递给函数

c++ - 为什么窗口在调用函数时需要大小?

c++ - std::string 对象的 xml 字符串

c - C中的字符串和字符连接

C++:链接器错误: undefined reference 仅对单独文件中定义的一个特定类成员