gpt4 book ai didi

c++ - map.find() 找不到关键 c++

转载 作者:太空宇宙 更新时间:2023-11-04 12:55:44 24 4
gpt4 key购买 nike

我正在以路径模式 (db/collection/_id) 从 MongoDB 中获取值,并尝试将数据插入到 map 中,其中 (Key=_id, value= full path)。但是,当我试图通过将键值传递给函数 map.find() 来查找某些 map 数据时,即使键存在,它也会返回 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);


}

最佳答案

如前所述,我们从 getline(&ptr, &len, stream) 中获取键中的换行符,删除该代码后,用户输入可以正常工作。我使用以下代码更正以删除换行符

key.erase(std::remove(key.begin(), key.end(), '\n'), key.end());

关于c++ - map.find() 找不到关键 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46801564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com