I have code as such:
typedef intptr_t ptr_t;
const int num_elements = 100;
ptr_t *pstr = (ptr_t *)malloc(sizeof(ptr_t) * num_elements);
std::array<ptr_t,num_elements> *parray = new (pstr) std::array<ptr_t,num_elements>;
I’d like to be able to shuffle elements 1 to num_elements-2 , so I thought to use std::shuffle.
auto s = parray->begin()++;
auto e = parray->end()--;
std::random_shuffle ( s, e );
I get a complaint that there is no overloaded function for this.
I’m feeling really stupid at my inability to see what I’m doing wrong. How do I do this right?
EDIT: due to answers and feedback, it has changed to
auto s = parray->begin();
s++;
auto e = parray->end();
std::random_shuffle ( s, e );
However, on the ‘auto e’ I get: ‘auto’ differs in levels of indirection from ‘int *’
In answer to your direct question: I believe your error is using the post increment operators, which return their original value before incrementing. Since
std::arrayiterators are basically pointers, tryEdit:
Now, as for the rest. Why on earth are you doing it that way? Have you considered
std::vector<int> arr(100)to create a dynamic array of 100 elements? It has similar capabilities, without all of the direct manipulation of pointers?Edit 2: After reading your comments, I realize the issue is that you’re trying to shuffle an array you were given as a pointer. In that case, I wouldn’t do the placement new at all. Assuming you have the pointer in
pstr, this should work.This works because simple pointers in an array will work as random access iterators for the purposes of the algorithm library.