Skip to content

Instantly share code, notes, and snippets.

@wobbol
Created October 25, 2017 21:23
Show Gist options
  • Save wobbol/aab2ad31fcad0b8319e0f29189938f81 to your computer and use it in GitHub Desktop.
Save wobbol/aab2ad31fcad0b8319e0f29189938f81 to your computer and use it in GitHub Desktop.
Using std::shuffle with a dynamically allocated vector that holds a custom class.
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <random>
class widget {
private:
int feet;
int inches;
public:
widget(int feet, int inches)
{
this->inches = inches%12;
this->feet = feet + inches/12;
return;
}
friend std::ostream& operator<<(std::ostream& os, const widget& f)
{
os << std::to_string(f.feet) << '\'';
os << std::to_string(f.inches) << '"';
return os;
}
};
void print(std::vector<widget> a)
{
std::cout << "contents: " << std::endl << "{ ";
for (auto x :a){
std::cout << x << ' ';
}
std::cout << "}" << std::endl;
return;
}
int main(void)
{
int num = 15;
unsigned int seed = 5;
std::vector<widget> arr;
for(int i = 0; i < num; ++i)
arr.emplace_back(0,i);
print(arr);
std::shuffle(arr.begin(), arr.end(), std::default_random_engine(seed));
print(arr);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment