I am fetching values from MongoDB in a path pattern (db/collection/_id) and trying to insert data into a map where (Key=_id, value= full path). However, while I am trying to find certain map data by passing the key value to the function map.find(), it is returning map.end() even though the key exists.
Below is the code I have implemented, please look into this and let me know where I am going wrong.
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);
}
As mentioned we are getting newline character in the keys from getline(&ptr, &len, stream)
and after removing that code works fine for user entries. I used below code to correct to remove newline characters
key.erase(std::remove(key.begin(), key.end(), '\n'), key.end());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.