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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With