vector::data

Returns a pointer to the first element in the vector.

const_pointer data() const;

Return Value

A pointer to the first element in the vector Class or to the location succeeding an empty vector.

Example

// vector_data.cpp
// compile with: /EHsc
#include <vector>
#include <iostream>
using namespace std;
int main()
{
    
   vector<int> vec;
    vector<int>::pointer pvec;
    vector<int>::const_pointer cpvec;

    vec.push_back(1);
    vec.push_back(2);

    // Iterate using direct pointer access, not iterators
    cout << "The vector contains:";
    cpvec = vec.data();
    for (size_t n = vec.size(); 0 < n; --n, ++cpvec)
    {
        cout << " " << *cpvec;
    }
    cout << endl;

    // Iterate using pointer and modify elements
    cout << "The vector now contains:";
    pvec = vec.data();
    *pvec = 20;
    for (size_t n = vec.size(); 0 < n; --n, ++pvec)
    {
        cout << " " << *pvec;
    }
    cout << endl;}
The vector contains elements: 1 2
The vector now contains elements: 20 2

Requirements

Header: <vector>

Namespace: std

See Also

Reference

vector Class

Standard Template Library