0

I have a vector : std::vector<const City*> cities

I want to write a funtion which will return me another vector with same type but in which the position of objects will be taken randomly.

std::vector<const City*> TSP::rand_cities() const  { }

Thank's for your help.

  • 1
    Create a copy of the original vector, apply `std::random_shuffle` and return it. – Matteo Italia Feb 13 '16 at 01:42
  • Or you could consider implementing the [Fisher Yates Shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle), if you want to write the function yourself (the question seems to indicate that you want to write it yourself). Just make sure to use a proper shuffling algorithm and that you use a good random number generator. – Andrew Feb 13 '16 at 01:45
  • I tried std::random_shuffle and get this error could not convert 'std::random_shuffle<__gnu_cxx::__normal_iterator > >(((const TSP*)this)- >TSP::cities.std::vector<_Tp, _Alloc>::begin >(), ((const TSP*)this)->TSP::cities.std::vector<_Tp, _Alloc>::end >())' from 'void' to 'std::vector' – kerrache massipssa Feb 13 '16 at 01:46
  • @kerrachemassipssa It looks like you tried `return std::random_shuffle(vec.begin(), vec.end());`. What you want is `std::random_shuffle(vec.begin(), vec.end()); return vec;` Where `vec` is my stand-in for whatever your vector is named. – user4581301 Feb 13 '16 at 01:52
  • It's what I did but it didn't work. – kerrache massipssa Feb 13 '16 at 02:01
  • The error message you posted says you tried to convert the `void` from `std::random_shuffle` to `vector`. Somewhere out there you have a `vec = std::random_shuffle(...)`. Here's a link to some reputable `random_shuffle` documentation: http://en.cppreference.com/w/cpp/algorithm/random_shuffle . Something is going wrong and maybe a refresher can help. – user4581301 Feb 13 '16 at 02:13

0 Answers0