C++ vector::data() 函数
vector::data() 是 "vector" 头文件的库函数,用于访问向量元素,它返回一个指向向量内部用于存储元素的内存数组的指针。
注意:要使用矢量,请包括<vector>
标题。
vector::data() 函数的语法
vector::data();
参数: none
——它什么都不接受。
返回值: value_type*
– 它返回一个指向向量内部使用的数组中第一个元素的指针。
例:
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++ 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;
}
输出
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
参考:C++ vector::data()
相关用法
- C++ vector::max_size()用法及代码示例
- C++ vector::rbegin()用法及代码示例
- C++ vector::pop_back()用法及代码示例
- C++ vector::crend()用法及代码示例
- C++ vector::push_back()用法及代码示例
- C++ vector::emplace_back用法及代码示例
- C++ vector::at()用法及代码示例
- C++ vector::swap()用法及代码示例
- C++ vector::shrink_to_fit()用法及代码示例
- C++ vector::cbegin()用法及代码示例
- C++ vector::back()用法及代码示例
- C++ vector::assign()用法及代码示例
- C++ vector::begin()用法及代码示例
- C++ vector::cend()用法及代码示例
- C++ vector::operator[]用法及代码示例
- C++ vector::clear()用法及代码示例
- C++ vector::cbegin()、vector::cend()用法及代码示例
- C++ vector::empty()用法及代码示例
- C++ vector::front()、vector::back()用法及代码示例
- C++ vector::at()、vector::swap()用法及代码示例
注:本文由纯净天空筛选整理自 vector::data() function with example in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。