C++中的数组类:高效替代C风格数组的现代选择

C++11 引入的 INLINECODEc069a812 类为我们提供了一个比传统 C 风格数组更好的选择。相较于 C 风格数组,INLINECODEaf0292d3 类的优势主要体现在以下几个方面:-

  • 知晓自身大小array 类知道它自己的大小,而 C 风格数组不具备这一特性。因此,当我们将其传递给函数时,不需要单独传递数组的大小参数。
  • 避免指针退化:使用 C 风格数组存在数组退化为指针的风险。而 array 类不会退化为指针,这在底层编程中是一个非常重要的安全特性。
  • 高效且可靠:一般来说,array 类比 C 风格数组更高效、更轻量,同时也更可靠。

数组上的操作

让我们深入了解 array 类提供的一些核心操作。

1. at() :- 这个函数用于访问数组中的元素。它与 operator[] 类似,但会进行边界检查。
2. get() :- 这个函数也可以用来访问数组元素。需要注意的是,它并不是 INLINECODE4cf95ea1 类的成员函数,而是来自 INLINECODEc66ca7eb 类的重载函数。
3. operator[] :- 这与 C 风格数组的用法非常相似。这个方法同样用于访问数组元素。

让我们通过代码来看看 INLINECODEc8f23b68 和 INLINECODEf689a1d5 是如何工作的:

CPP


CODEBLOCK_2b2415c5

Output

The array elements are (using at()) : 1 2 3 4 5 6 
The array elements are (using get()) : 1 2 3 4 5 6 
The array elements are (using operator[]) : 1 2 3 4 5 6

接下来,让我们看看如何访问数组的头部和尾部。

4. front() :- 该函数返回数组第一个元素的引用。
5. back() :- 该函数返回数组最后一个元素的引用。

下面是 INLINECODE0e00fbde 和 INLINECODE302e556c 的演示代码:

CPP


CODEBLOCK_7c41c89e

Output

First element of array is : 1
Last element of array is : 6
array after updating first and last element 
10 2 3 4 5 60

了解数组的大小也是非常重要的。

6. size() :- 它返回数组中元素的个数。这是 C 风格数组所不具备的一个属性。
7. maxsize() :- 它返回数组所能容纳的最大元素数量,即在声明数组时指定的大小。对于 INLINECODE2914249e 类,INLINECODEbb95ecf4 和 INLINECODEb0963096 返回的值是相同的。

CPP


CODEBLOCK_4a8e650c

Output

The number of array elements is : 6
Maximum elements array can hold is : 6

最后,我们来看看如何交换两个数组的内容。

8. swap() :- swap() 函数可以将一个数组的所有元素与另一个数组进行交换。

CPP


// C++ code to demonstrate working of swap()

#include

#include // for swap() and array

using namespace std;

int main()

{

// Initializing 1st array

array ar = {1, 2, 3, 4, 5, 6};

// Initializing 2nd array

array ar1 = {7, 8, 9, 10, 11, 12};

// Printing 1st and 2nd array before swapping

cout << "The first array elements before swapping are : ";

for (int i=0; i<6; i++)

cout << ar[i] << " ";

cout << endl;

cout << "The second array elements before swapping are : ";

for (int i=0; i<6; i++)

cout << ar1[i] << " ";

cout << endl;

// Swapping ar1 values with ar

ar.swap(ar1);

// Printing 1st and 2

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/44385.html
点赞
0.00 平均评分 (0% 分数) - 0