lundi 6 juillet 2015

How to create std::map with key value random

I am testing speed of writing a std::map(std::string, std::string) to file in hardisk (using serialization of Boost). So I need create a map with a lot of element in map. I have a problem when create random keys for map. Here is my code to generate map:

#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <sstream>
#include <chrono>

using namespace std;

string randomString(int len) {
    srand(time(0));
    string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    int pos;
    while (str.size() != len) {
        pos = ((rand() % (str.size() - 1)));
        str.erase(pos, 1);
    }
    return str;
}

void save() {
    std::map<std::string, std::string> myMap;
    string key;
    string value;
    for (int i = 0; i < 50; i++) {
        myMap[randomString(20)] = randomString(20);
    }

    cout << "Map size: " << myMap.size() << endl;

    for (map<string, string>::iterator ii = myMap.begin(); ii != myMap.end(); ++ii) {
        cout << (*ii).first << ": " << (*ii).second << endl;
    }
}

int main() {
    save();
    return 0;
}

In for loop, the keys are the same so my map has only one element. What is wrong with code? Please help me and do you have different way to create map with random elements. Thanks so so much!




Aucun commentaire:

Enregistrer un commentaire