stl vector 函数_vector :: data()函数以及C ++ STL中的示例

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

参考: C ++ vector :: data()

翻译自: https://www.includehelp.com/stl/vector-data-function-with-example.aspx

stl vector 函数

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值