Multimap

I'm working on a project right now where my program reads a text file, and encodes the text file with the character locations from another text file.

Right now I have a multimap, that inputs the characters from the text file, and there locations. What I want to do now is randomly pick one of the numbers from the list of numbers that are related to that character.

For example:
A:0
A:26
A:48
A:128

I want to somehow randomly pick one of those numbers.
Any help would be greatly appreciated.
I suggest that you load all those values into an array - of integers, for example - once that is done generate a random number, modulus it with the size of your array & then that is the number to choose, for example:

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
  int myArray[] = {0, 26, 48, 128};
  srand(time(NULL));
  printf("%d\n", myArray[rand() % 4]);
  return 0;
}


Rand reference: http://www.cplusplus.com/reference/clibrary/cstdlib/rand/
Srand reference: http://www.cplusplus.com/reference/clibrary/cstdlib/srand/
You can:

1
2
3
4
5
6
// Assume:
std::multimap<char, int> m;

std::multimap<char, int>::const_iterator i( m.begin() );
std::advance( m, rand() % m.size() );
std::cout << "The number is " << i->second << std::endl;


(Note that std::advance() is O(n) complexity in this case, though not worse
than converting the data structure to an array first).

I'm trying to do something like the Array but I'm getting an error how would I go about getting this to work?
1
2
3
int myArray[] = bookMap.equal_range('a');
			srand(time(NULL));
			printf("%d\n", myArray[rand() % (int)bookMap.count('a')]);
I imagine you can see what I'm trying to do, get the numbers that correspond to a into the array, would creating a for loop, and iterating over the equal range then putting the *it into the array work?
workman845: I gave you a complete solution that doesn't require copying the
data into an array. I suggest you use it and forget the array approach.
I've never heard/used "advance" before, I'm getting errors, and I don't know why.
This is the code I tried to use
1
2
3
std::multimap<char, int>::const_iterator it( bookMap.begin() );
			std::advance( bookMap, rand() % bookMap.size() );
			std::cout << "The number is " << it->second << std::endl;
Okay, I figured it out, but it's never random, it just seems to use the last element of that type.

1
2
3
multimap<char,int>::iterator a; a = bookMap.equal_range('a').first;
			advance( a, rand() % (int)bookMap.count('a') );
			cout << "The number is " << a->second << endl;
Did you call srand() in your program to seed the rng?
Oops! haha works now thank you very much.
Topic archived. No new replies allowed.