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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。