C++ Array::data() 函数



C++ 的std::array::data()函数提供了一个指向数组容器使用的底层数组的直接指针。此函数返回指向数组第一个元素的指针,允许访问内部数据。

语法

以下是 std::array::data() 函数的语法。

value_type* data() noexcept;
const value_type* data() const noexcept;

参数

它不接受任何参数。

返回值

它返回一个指向数组对象包含的数据的指针。

异常

此函数永远不会抛出异常。

时间复杂度

常数,即 O(1)

示例 1

在以下示例中,我们将考虑 data() 函数的基本用法。

#include <iostream>
#include <array>
using namespace std;
int main(void) {
   array < char, 128 > s = {"C++ standard library from tutorialspoint.com"};
   char * p, * q;
   p = s.data();
   cout << p << endl;
   q = p;
   while ( * q) {
      cout << * q;
      ++q;
   }
   cout << endl;
   return 0;
}

输出

以上代码的输出如下:

C++ standard library from tutorialspoint.com
C++ standard library from tutorialspoint.com

示例 2

考虑以下示例,我们将对整数数组应用 data() 函数。

#include <iostream>
#include <array>
using namespace std;
int main() {
   array < int, 10 > arr = {9,12,15,18,21,24,27,30,33,36};
   cout << "The array elements are ";
   for (auto it = arr.begin(); it != arr.end(); it++)
      cout << * it << " ";
   auto it = arr.data();
   cout << "\nThe first element = " << * it;
   it++;
   cout << "\nThe second element = " << * it;
   it++;
   cout << "\nThe third element = " << * it;
   return 0;
}

输出

以下是以上代码的输出:

The array elements are 9 12 15 18 21 24 27 30 33 36 
The first element = 9
The second element = 12
The third element = 15

示例 3

让我们看看以下示例,我们将考虑字符数组并应用 data() 函数。

#include <iostream>
#include <array>
using namespace std;
int main() {
   array < char, 3 > x = {'a','n','u'};
   cout << "The array elements are = ";
   for (auto it = x.begin(); it != x.end(); it++)
      cout << * it << " ";
   auto it = x.data();
   cout << "\nThe first element = " << * it;
   return 0;
}

输出

如果我们运行以上代码,它将生成以下输出:

The array elements are = a n u 
The first element = a
array.htm
广告

© . All rights reserved.