stl - 字符串是一个向量? [英] stl - Is a string a vector?
问题描述
我在一些测验中遇到了一个问题
是字符串是向量吗?如果是,以什么方式? >
两者都可以随机访问内容。
但是字符串有一些方法向量dosn`t.It也可能有引用计数。
所以显然字符串不是一个向量(typedef字符串向量)
是否有已知的实现 class string:public vector< char>
?
I have encountered a question in some quiz
"Is a string a vector? If yes, in what way? If no, why not?
"
Both of them have random access to the content.
But string has some methods which vector dosn`t.It also might have reference count .
So it is obvious that string is not exactly a vector (typedef string vector)
Are there known implementations in which class string : public vector <char>
?
If not - what is the reason for not implementing it so?
推荐答案
从纯哲学的角度来看:是的,字符串是向量的类型。它是存储字符的连续内存块(向量是存储任意类型对象的连续内存块)。因此,从这个角度来看,字符串是一种特殊的向量。
From a purely philosophical point of view: yes, a string is a type of vector. It is a contiguous memory block that stores characters (a vector is a contiguous memory block that stores objects of arbitrary types). So, from this perspective, a string is a special kind of vector.
在设计和实现 std :: string
和 std :: vector
,它们共享一些相同的接口元素(例如连续的内存块, operator []
),但是 std :: string
不会不从 std :: vector
(旁注:你不应该公开派生自标准容器,因为它们不是基于类的 - 例如它们没有虚拟析构函数),也不能直接互相转换。也就是说,以下不会编译:
In terms of design and implementation of std::string
and std::vector
, they share some of the same interface elements (e.g. contiguous memory blocks, operator[]
), but std::string
does not derive from std::vector
(side note: you should not publicly derive from standard containers as they are not designed to be based classes - e.g. they do not have virtual destructors), nor are they directly convertible to each other. That is, the following will not compile:
std::string s = "abc";
std::vector<char> v = s; // ERROR!
但是,由于它们都支持迭代器,因此可以将字符串转换为向量:
However, since they both have iterator support, you can convert a string to a 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
will no longer have a reference count (as of C++11) as the copy-on-write functionality that many implementations used was forbidden by the C++11 standard.
从内存角度来看, std :: string
的实例会看起来非常类似到 std :: vector< char>
(例如,它们都将具有指向它们的存储器位置,大小,容量的指针),但是两个类是不同的。
From a memory perspective, an instance of std::string
will look very similar to a std::vector<char>
(e.g. they both will have a pointer to their memory location, a size, a capacity), but the functionality of the two classes is different.
这篇关于stl - 字符串是一个向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!