尝试使用从 ptr_map::find 返回的迭代器时出错

Error trying to use iterator returned from ptr_map::find

本文关键字:返回 find 迭代器 出错 map ptr      更新时间:2023-10-16

我在下面的代码上收到编译错误。错误是:

/ ... /main.cpp:21:22: error: no member named 'name' in 'boost::ptr_container_detail::ref_pair<std::__1::basic_string<char>, repo *const>'
    std::cout << it->name;
                 ~~  ^

我在这里做错了什么?我已经尝试了 it.name 和它>名称,但都不起作用。

问候,大卫。

#include <boost/ptr_container/ptr_map.hpp>
class repo {
public:
    repo(const std::string & repo_name) : name(repo_name) {}
    std::string name;
};
typedef boost::ptr_map<std::string, repo> repo_map;
repo_map repos;
int main() {
    std::string repo_name("x");
    repo_map::iterator it = repos.find(repo_name);
    if (it == repos.end()) {
        it = repos.insert(repo_name, new repo(repo_name)).first;
    }
    std::cout << it->name;
    return 0;
}

因为它是一个 ptr_map,所以它返回pair<key, ptr_value> 。所以你需要:

it->second->name

我认为这将完成工作

它->second.name