当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ vector::data()用法及代码示例


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()



相关用法


注:本文由纯净天空筛选整理自 vector::data() function with example in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。