我从路径模式(db / collection / _id)中获取MongoDB中的值,并尝试将数据插入到地图中(Key = _id,value = full path)。但是,当我试图通过将键值传递给函数map.find()来查找某些地图数据时,即使该键存在,它也会返回map.end()。
以下是我实施的代码,请仔细阅读并告知我出错的地方。
class myStructure {
std::vector<string> arr;
public:
std::map<std::string, std::string> myMap;
public:
void add(char *ptr, size_t len, FILE *stream) {
std::string key;
unsigned found;
while (getline(&ptr, &len, stream) != -1) {
std::string path(ptr);
found = path.find_last_of("/\\");
key = path.substr(found + 1);
myMap[key] = path;
}
// Iterating entire Map
std::map<string, string>::iterator its1 = myMap.begin();
std::cout << "myMap contains:\n";;
for (its1 = myMap.begin(); its1 != myMap.end(); ++its1)
std::cout << its1->first << " => " << its1->second << '\n';
// Output
//59dd9db3b3defb36a894a0f1 => /test/restaurants/59dd9db3b3defb36a894a0f1
std::string key_to_erase;
std::cout << "Enter Key value to remove:" << std::endl;
std::cin >> key_to_erase;
//Erasing provided key value
std::map<std::string, std::string>::iterator iit = myMap.find(key_to_erase);
if (iit == myMap.end()) {
std::cout << "key not found\n";
}
// Check if iterator is valid.
else {
// Remove the element pointed by iterator
myMap.erase(key_to_erase);
std::cout << "Element Removed" << std::endl;
}
}
};
int main(int, char**)
{
FILE *fpipe;
std::string file;
char *command = "/usr/bin/mongo --eval \"db.getSiblingDB(\\\"admin\\\").runCommand({ \\\"listDatabases\\\": 1 }).databases.forEach(function(database) {db = db.getSiblingDB(database.name);cols = db.getCollectionNames();cols.forEach(function(collectionName) {collection=db.getCollection(collectionName);keys=collection.find();keys.forEach(function(key){print(\\\"/\\\"+db+\\\"/\\\"+collectionName+\\\"/\\\"+key._id);});});});\"";
//input values
/*test/restaurants/59dd9db4b3defb36a894cd31
test/restaurants/59dd9db4b3defb36a894cd32
test/restaurants/59dd9db4b3defb36a894cd33
test/restaurants/59dd9db4b3defb36a894cd34*/
char *ptr = NULL;
size_t len;
std::array<char, 128> buffer;
FILE *stream = popen (command, "r");
myStructure ds;
ds.add(ptr, len, stream);
}
答案 0 :(得分:0)
如前所述,我们在getline(&ptr, &len, stream)
的密钥中获取换行符,并且在删除该代码后,用户条目工作正常。我使用下面的代码来纠正删除换行符
key.erase(std::remove(key.begin(), key.end(), '\n'), key.end());