STL array的operator[]方法(15)

来源:互联网 发布:艾灸淘宝推广文章 编辑:程序博客网 时间:2024/05/16 06:54
原文地址:http://www.cplusplus.com/reference/array/array/operator[]/
public member function
<array>

std::array::operator[]

      reference operator[] (size_type n);const_reference operator[] (size_type n) const;
Access element
Returns a reference to the element at position n in the array container.

返回array容器中位置为n的元素的引用。


A similar member function, array::at, has the same behavior as this operator function, except that array::at checks the array bounds and signals whether n is out of range by throwing an exception.

一个相似的方法是at,和该方法有相同的行为,但是at会检测范围的合法性,并且如果n超出范围会抛出异常。

例子:

#include <iostream>#include <array>using namespace std;int main(){array<int,3> ai{10,20,30};cout<<"ai[-1]="<<ai[-1]<<endl;cout<<"ai[0]="<<ai[0]<<endl;cout<<"ai[1]="<<ai[1]<<endl;cout<<"ai[2]="<<ai[2]<<endl;cout<<"ai[5]="<<ai[5]<<endl;}
运行结果:


可以看到,operator[]不会检测n的合法性。



Parameters

n

Position of an element in the array.

Notice that the first element has a position of 0, not 1.
Member type size_type is an alias of the unsigned integral type size_t.

array中元素的位置。

注意第一个元素位置是0而不是1.


Return value

The element at the specified position in the array.

返回指定位置元素的引用。


If the array object is const-qualified, the function returns a const_reference. Otherwise, it returns a reference.

如果array是const的,那么返回的将是const引用。


Member types reference and const_reference are the reference types to the elements of the array (see array member types).

Example

1234567891011121314151617181920
// array::operator[]#include <iostream>#include <array>int main (){  std::array<int,10> myarray;  unsigned int i;  // assign some values:  for (i=0; i<10; i++) myarray[i]=i;  // print content  std::cout << "myarray contains:";  for (i=0; i<10; i++)    std::cout << ' ' << myarray[i];  std::cout << '\n';  return 0;}
Edit & Run


Output:
myarray contains: 0 1 2 3 4 5 6 7 8 9

Complexity

Constant.

Iterator validity

No changes.

Data races

The reference returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.

返回的引用可以用来访问以及修改元素,同时访问以及修改不同的元素是安全的。


Exception safety

If the container size is greater than n, the function never throws exceptions (no-throw guarantee).

如果容器的size大于n,不会抛出异常。

Otherwise, it causes undefined behavior.

否则,会导致未定义的行为。


——————————————————————————————————————————————————————————————————

//翻译的不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。

转载请注明出处:http://blog.csdn.net/qq844352155
author:天下无双

2014-8-30

于GDUT


——————————————————————————————————————————————————————————————————





0 0
原创粉丝点击