stl vector 函数
C ++ vector :: data()函数 (C++ vector::data() function)
vector::data() is a library function of "vector" header, it is used to access the vector elements, it returns a pointer to the memory array used by the internally by the vector to store the elements.
vector :: data()是“ vector”头文件的库函数,用于访问矢量元素,它返回一个指针,该指针指向矢量内部用于存储元素的内存数组。
Note: To use vector, include <vector> header.
注意:要使用向量,请包含<vector>标头。
Syntax of vector::data() function
vector :: data()函数的语法
vector::data();
Parameter(s): none – It accepts nothing.
参数: 无 –不接受任何内容。
Return value: value_type* – It returns a pointer to the first element in the array used internally by the vector.
返回值: value_type * –返回一个指针,该指针指向向量内部使用的数组中的第一个元素。
Example:
例:
Input:
vector<int> vector1{ 1, 2, 3, 4, 5 };
//declare a pointer of same type
int* ptr = vector1.data();
Accessing elements:
cout << *ptr << endl;
ptr++;
cout << *ptr << endl;
Output:
1
2
C ++程序演示vector :: data()函数的示例 (C++ program to demonstrate example of vector::data() function)
//C++ STL program to demonstrate example of
//vector::data() function
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v1{ 10, 20, 30, 40, 50 };
//declare a pointer of same type
int* ptr = v1.data();
//printing all elements
//using vector::data() function
cout << "all elements of vector v1..." << endl;
for (int i = 0; i < v1.size(); i++) {
cout << "element at index " << i << " : " << *ptr << endl;
//increasing pointer
ptr++;
}
//updating some elements
//initializing the pointer again
ptr = v1.data();
*(ptr + 0) = 100;
*(ptr + 1) = 200;
*(ptr + 2) = 300;
//after updating, printing all elements
//using vector::data() function
cout << "all elements of vector v1..." << endl;
for (int i = 0; i < v1.size(); i++) {
cout << "element at index " << i << " : " << *ptr << endl;
//increasing pointer
ptr++;
}
return 0;
}
Output
输出量
all elements of vector v1...
element at index 0 : 10
element at index 1 : 20
element at index 2 : 30
element at index 3 : 40
element at index 4 : 50
all elements of vector v1...
element at index 0 : 100
element at index 1 : 200
element at index 2 : 300
element at index 3 : 40
element at index 4 : 50
Reference: C++ vector::data()
翻译自: https://www.includehelp.com/stl/vector-data-function-with-example.aspx
stl vector 函数