I want to create a vector of integers. Once created I want to shuffle the intergers in order to have a random order of integers. This will be used for testing the sorting functions.
Now no sorting algorithm will be allowed to sort the vector inplace and hence we need to make the vector a constant. Also - I do not want anyone to be able to change the unique_ptr and point it to something else.
Q1. How do we achieve it.
Currently solution :
After reading this and this and other references, I have done the following.
I am creating a vector, assign it to unique pointer to make sure that it is guarded against memory leaks and gets automatically deleted when we go out of scope. We shuffle the vector and then move this vector to a new one which has type as (const std::vector ). We then move the pointer to a const unique pointer.
In the code below I have coded the current solution. Let me know if there is a better way of doing it.
#include <random>
#include <memory>
#include <algorithm>
#include <iostream>
#include <vector>
std::unique_ptr<const std::vector <int>> createConstVector(int numberOfElements, int increments) {
auto v = std::make_unique <std::vector<int>> (numberOfElements);
std::random_device rd;
std::mt19937 g(rd());
std::generate(v->begin(), v->end(), [n=0, increments] () mutable { n = n + increments; return n;});
std::shuffle(v->begin(), v->end(), g);
std::unique_ptr<const std::vector<int>> v2 = std::move(v);
return std::move(v2);
}
auto sortUsingStdSort(std::unique_ptr<const std::vector<int>> const &vectorToSort) {
std::unique_ptr<std::vector<int>> v = std::make_unique<std::vector<int>> (*vectorToSort);
std::sort(v->begin(), v->end());
return std::move(v);
}
int main () {
const std::unique_ptr<const std::vector <int>> u3 = createConstVector(10, 5);
auto sortedVector = sortUsingStdSort(u3);
for(auto v : *sortedVector) {
std::cout << " " << v;
}
}
Aucun commentaire:
Enregistrer un commentaire