字符串下标是关联索引吗?

Is string subscript an associated index?

The subscript operator ([]) takes a std::string::size_type value. The operator returns a reference to the character at the given position. The value in the subscript is referred to as "a subscript" pp93 ~ 94 C++ Primer 5ed.

A vector is a collection of objects, all of which have the same type. Evey object in the collection has an associated index, which gives access to that object.pp96 C++ Primer 5ed.

问题:

字符串下标是关联索引吗?如果不是,std::string类型的下标和collection/vector类型的关联索引有什么区别?

将 "index" 视为 "the sequential number of an item," 而不是将 "index" 视为 "the lookup table in a book."

他们所说的关于向量的内容是可以通过顺序数字索引访问其中的元素:v[0]v[1]

字符串和其中的字符完全相同。

根据std::vector::operator[],函数:

Returns a reference to the element at specified location pos. No bounds checking is performed.

根据std::basic_string::operator[],函数:

Returns a reference to the character at specified location pos. No bounds checking is performed. If pos > size(), the behavior is undefined.

因此,它们几乎是一回事。术语关联索引的意思正是它听起来的意思;它是与元素关联的索引,仅此而已。

这里的措辞比较准确,但是这两个简单的案例并没有真正的区别。对于stringvectorX[0]表示X的第一个元素。也就是说,0是X的第一个元素的关联索引,0也是X的参数operator[],又名下标。

要查看不那么简单的示例,请考虑 std::string_view。您可以在字符串的第 100 到第 200 个字符中使用 string_view。现在 view[5] 有下标 5,但它指的是基础字符串中的第 105 个字符。