I\'m using a external library which at some point gives me a raw pointer to an array of integers and a size.
Now I\'d like to use std::vector
to access and
Since the algorithm-library works with iterators you can keep the array.
Here you can use raw pointers as iterators. They support all the opertations an iterator supports (increment, comparison for equality, value of, etc...):
#include
#include
int *get_data_from_library(int &size) {
static int data[] = {5,3,2,1,4};
size = 5;
return data;
}
int main()
{
int size;
int *data = get_data_from_library(size);
std::sort(data, data + size);
for (int i = 0; i < size; i++)
{
std::cout << data[i] << "\n";
}
}
data
points to the dirst array member like an iterator returned by begin()
and data + size
points to the element after the last element of the array like an iterator returned by end()
.
Here you can use std::begin()
and std::end()
#include
#include
int main()
{
int data[] = {5,3,2,1,4}; // raw data from library
std::sort(std::begin(data), std::end(data)); // sort raw data in place
for (int i = 0; i < 5; i++)
{
std::cout << data[i] << "\n"; // display sorted raw data
}
}
But keep in mind that this only works, if data
does not decay to a pointer, because then length information goes missing.