我在一些测验中遇到了一个问题
“ 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::string
和 std::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/