Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between begin() and data()

Tags:

c++

stl

vector

begin() and data() both returns iterator pointing to the first element. But, the definition of data() says it Returns a direct pointer to the memory array used internally by the vector to store its owned elements. I can also use them to access any element. So, how both of them are different? consider the following example,

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v;
    v.reserve(5);

    for (int i = 1; i <= 5; i ++) v.push_back(i);
    
    auto it = v.begin();
    auto pos = v.data();

    std::cout << "First element : " << *it << std::endl;
    std::cout << "First element : " << *pos << std::endl;

    std::cout << "Third element : " << it[2] << std::endl;
    std::cout << "Third element : " << pos[2] << std::endl;
}
like image 682
Somya Sarathi Samal Avatar asked Nov 29 '25 08:11

Somya Sarathi Samal


1 Answers

std::vector::begin()

v.begin() returns an iterator referring to the first element in the vector.

std::vector::data()

v.data() returns a pointer to the first element in the array used internally by the vector.

like image 136
artist.pradeep Avatar answered Dec 01 '25 22:12

artist.pradeep