Random shuffle, pairing of objects using string attribute

How to use random _shuffle(), to pair up object/instance using its string attribute? Thanks in advance!

void game1(void)
{
srand(time(nullptr));

const set<string> values{ }; //I don't know how to add my string //attribute here

for (auto pair : make_unique_pairs(values))
cout << pair.first << ',' << pair.second << '\n';
}

void main()

template < typename T >
vector< pair<T, T> > make_unique_pairs(const set<T>& set)
{
vector< pair<T, T> > result;

// make a vector of references to elements in the set
vector< reference_wrapper< const T > > seq(set.begin(), set.end());

// make a random permutation of the references
random_shuffle(begin(seq), end(seq));

// make pairs and place them into the result
for (size_t i = 0; i < seq.size() - 1; i += 2)
result.emplace_back(seq[i], seq[i + 1]);

return result;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
template < typename T > std::vector< std::pair<T,T> > make_random_pairs( const std::set<T>& set )
{
    std::vector< std::reference_wrapper< const T > > seq( set.begin(), set.end() );

    std::shuffle( std::begin(seq), std::end(seq), std::mt19937( std::random_device{}() ) ) ;
    if( seq.size() % 2 ) seq.pop_back() ; // make size an even number

    std::vector< std::pair<T,T> > result ;
    for( std::size_t i = 0 ; i < seq.size() ; i += 2 ) result.emplace_back( seq[i], seq[i+1] ) ;
    return result ;
}

void game_1()
{
    const std::set<std::string>& values
    { "abhogi", "kamboji", "bhairavi", "atana", "kanada", "todi", "sri", "ranjini", "sama", "kapi", "begada" };

    for( auto pair : make_random_pairs(values) )
        std::cout << std::setw(10) << std::quoted(pair.first) << "  -  " << std::quoted(pair.second) << '\n';
}

http://coliru.stacked-crooked.com/a/623391f6380cb9c8
Topic archived. No new replies allowed.