访问元素
|
c.back() |
返回容器 c 的最后一个元素的引用。如果 c 为空,则该操作未定义 |
|
c.front() |
返回容器 c 的第一个元素的引用。如果 c 为空,则该操作未定义 |
|
c[n] |
返回下标为 n 的元素的引用如果 n <0 或 n >= c.size(),则该操作未定义只适用于 vector 和 deque 容器 |
|
c.at(n) |
返回下标为 n 的元素的引用。如果下标越界,则该操作未定义只适用于 vector 和 deque 容器 |
// check that there are elements before dereferencing an iterator
// or calling front or back
if (!ilist.empty()) {
// val and val2 refer to the same element
list<int>::reference val = *ilist.begin();
list<int>::reference val2 = ilist.front();
// last and last2 refer to the same element
list<int>::reference last = *--ilist.end();
list<int>::reference last2 = ilist.back(); }
这段程序使用了两种不同的方法获取时 ilist 中的第一个和最后一个元素的引用。 直接的方法是调用 front 或 back 函数。 间接的方法是, 通过对 begin操作返回的迭代器进行解引用,或对 end 操作返回的迭代器的前一个元素位置进行解引用,来获取对同一元素的引用。在这段程序中,有两个地方值得注意:
end 迭代器指向容器的超出末端的下一位置,因此必须先对其减 1 才能获取最
后一个元素;另一点是,在调用 front 或 back 函数之前,或者在对 begin 或end 返回的迭代器进行解引用运算之前,必须保证 ilist 容器非空。如果该list 容器为空,则 if 语句内所有的操作都没有定义。
使用 front 或 back 运算时, 必须注意同样的问题。 如果容器为空, 那么这些操作将产生未定义的结果。
如果容器内只有一个元素,则 front 和 back 操作都返回对该元素的引用。使用越界的下标,或调用空容器的 front 或 back 函数,都会导致程序出现严重的错误。
使用下标运算的另一个可选方案是 at 成员函数。这个函数的行为和下标运算相似,但是如果给出的下标无效,at 函数将会抛出 out_of_range异常:
vector<string> svec; // empty vector
cout << svec[0]; // run-time error: There are no elements in svec!
cout << svec.at(0); // throws out_of_range exception

浙公网安备 33010602011771号