STL array的operator[]方法(15)

原文地址: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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 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;
}


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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值