Multimap

Mar 19, 2010 at 5:05pm
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.
Mar 19, 2010 at 5:46pm
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/
Mar 20, 2010 at 1:46am
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).

Mar 20, 2010 at 4:53pm
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?
Mar 20, 2010 at 7:47pm
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.
Mar 20, 2010 at 8:13pm
I've never heard/used "advance" before, I'm getting errors, and I don't know why.
Mar 20, 2010 at 8:18pm
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;
Mar 20, 2010 at 9:13pm
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;
Mar 21, 2010 at 4:10pm
Did you call srand() in your program to seed the rng?
Mar 21, 2010 at 6:48pm
Oops! haha works now thank you very much.
Topic archived. No new replies allowed.