1
我從路徑模式(db/collection/_id)中獲取MongoDB中的值並嘗試將數據插入映射中(Key = _id,value = full path)。但是,儘管我試圖通過將密鑰值傳遞給函數map.find()來查找某些地圖數據,但即使該密鑰存在,也會返回map.end()。map.find()找不到鍵C++
下面是我已經實施的代碼,請看看這個,讓我知道我要去哪裏錯了。
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);
}
如果沒有前導空格,您的修剪功能好像會留下尾隨空格。嘗試在遍歷地圖時圍繞正在打印的內容添加引號,以確保沒有任何不可見的左側。 'std :: cout <<「'」<< its1->第一個<< "' =>「<< its1->第二個<<'\ n';' –
另外,'std :: cin >> key_to_erase'已經被修剪,所以'trim(key_to_erase)'是多餘的。 '運算符>>'在掃描前忽略前導空白,然後在遇到空白時停止掃描 –
我已經嘗試過沒有修剪功能。您可以通過刪除修剪功能在您的端測試此代碼 –