官术网_书友最值得收藏!

Arrays

An array is the basic data structure that provides a collection of data contiguously stored in memory. Many adapters, such as the stack, are implemented using arrays. Their uniqueness is that array elements are all of the same type, which plays a key role in accessing array elements. For example, the following declaration creates an array of 10 integers:

int arr[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

The name of the array decays to a pointer to its first element. Considering the fact that array elements have the same type, we can access any element of the array by advancing the pointer to its first element. For example, the following code prints the third element of the array: 

std::cout << *(arr + 2);

The same goes with the first element; the following three lines of code are doing the same thing:

std::cout << *(arr + 0);
std::cout << *arr;
std::cout << arr[0];

To make sure that arr[2] and *(arr + 2) do the exact same thing, we can do the following:

std::cout << *(2 + arr);

Moving the 2 behind the + won't affect the result, so the following code is valid as well:

std::cout << 2[arr];

And it prints the third element of the array.

An array element is accessed in constant time, which means accessing the first and the last elements of the array takes the same amount of time. It's because every time we access an array element, we do the following:

  1. Advance the pointer by adding the corresponding numeric value
  2. Read the contents of memory cells placed at the result pointer 

The type of the array indicates how many memory cells should be read (or written). The following diagram illustrates the access:

This idea is crucial when creating dynamic arrays, which are arrays that are located in the heap rather than the stack. As we already know, allocating memory from the heap gives the address of its first byte, so the only chance to access elements other than the first one, is by using pointer arithmetic:

int* arr = new int[10];
arr[4] = 2; // the same as *(arr + 4) = 2

We will discuss more about the structure of arrays and other data structures in Chapter 6Digging into Data Structures and Algorithms in STL.

主站蜘蛛池模板: 桂东县| 洛阳市| 辰溪县| 德安县| 丰都县| 普安县| 穆棱市| 天等县| 昌黎县| 星子县| 霍城县| 湘乡市| 曲靖市| 东莞市| 临猗县| 潍坊市| 益阳市| 张家界市| 肃南| 新巴尔虎右旗| 武夷山市| 蓝山县| 东海县| 云安县| 德阳市| 信阳市| 灌南县| 浮梁县| 富民县| 海盐县| 宽城| 孝感市| 镇康县| 昌黎县| 鹤峰县| 仁怀市| 阿拉善盟| 伊川县| 无锡市| 肥西县| 乌兰察布市|