I found an example of std::vector in http://www.cplusplus.com/reference/vector/vector/data/.
// vector::data
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector (5);
int* p = myvector.data();
*p = 10;
++p;
*p = 20;
p[2] = 100;
std::cout << "myvector contains:";
for (unsigned i=0; i<myvector.size(); ++i)
std::cout << ' ' << myvector[i];
std::cout << '\n';
return 0;
}
and the result is
myvector contains: 10 20 0 100 0
My question may be silly but I don't really understand what happened here. We got a direct pointer to the memory of the vector. Then we assign the value 10 for the first element (index 0), move to the second element and assign the value 20 to it (index 1). Finally, we assign the value 100 for the third element (index 2). Should the answer be as follow?
10 20 100 0 0
vector data() function in C++ STL The std::vector::data() is an STL in C++ which returns a direct pointer to the memory array used internally by the vector to store its owned elements.
The most idiomatic way is to make your function take iterators: template<typename It> It::value_type maxsubarray(It begin, It end) { ... } and then use it like this: std::vector<int> nums(...); auto max = maxsubarray(begin(nums) + 2, end(nums));
Indexing works on Vectors, So just Acces it by using index.
This picture might help explain
int* p = myvector.data();
[ ] [ ] [ ] [ ] [ ]
^
*p = 10;
[10 ] [ ] [ ] [ ] [ ]
^
++p;
[10 ] [ ] [ ] [ ] [ ]
^
*p = 20;
[10 ] [20 ] [ ] [ ] [ ]
^
p[2] = 100; // [2] is relative to where p is
[10 ] [20 ] [ ] [100] [ ]
^
The output of the example is right. Let me demonstrate it below -
std::vector<int> myvector (5); // creating vector with size 5, elements are 0,0,0,0,0
int* p = myvector.data(); //taking reference of the vector, p now points the first element of vector
*p = 10; // it means first element is now 10
++p; // p now points second element of the vector
*p = 20; // 2nd element is now 20
p[2] = 100; //p[2] is the 4th element now because of two position shifting and it is now 100
// vectors elements are now 10, 20, 0, 100, 0
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