我正在测试将 std::map(std::string, std::string) 写入硬盘文件的速度(使用 Boost 序列化)。所以我需要在 map 中创建一个包含很多元素的 map 。为 map 创建随机键时遇到问题。这是我生成 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;
}
在 for 循环中,键是相同的,所以我的 map 只有一个元素。代码有什么问题?请帮助我,你有不同的方法来创建随机元素的 map 。
最佳答案
每次调用randomString
时都会调用srand
,由于time
函数返回的时间只有秒分辨率,如果调用randomString
在同一秒内多次调用,所有这些调用都会设置相同的种子,导致您拥有相同的“随机”序列。
仅在程序开始时调用 srand
一次。
关于c++ - 如何使用随机键值创建 std::map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31243713/