How can I change the code below to have unique_ptr instead of the traditional pointer?
// 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;
}
I tried the code below, but I am having E0349 no operator "++" matches these operands
unique_ptr<int> p {myvector.data()};
*p = 10;
++p; // <<< ERROR HERE >>>
Smart pointers are not meant to manage individual elements of bulk data. The intent purpose of smart pointers is to manage the allocation and lifetime of complex objects.
Container objects like std::vector have iterators for the express purpose to wrap access to their bulk data internal elements without exposing a naked pointer. Use those!
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