关于地图::擦除和地图::计数

Regarding map::erase and map::count

本文关键字:地图 擦除 计数 于地图      更新时间:2023-10-16

我只是简单地问了一个关于map::count()和map::erase()的使用的问题。我将这些与std::string一起使用,但我想知道是否需要使用string::c_str()。例如,我的代码当前显示为:

void Person::removeFriend(std::string first, std::string last){
    std::string name = (first + last);
    //checks to ensure the friend exists in the user's friend list
    if (_friends.count(name) == 1){
        _friends.erase(name);
    }
}

所以我的问题是,它真的应该这样出现吗:

void Person::removeFriend(std::string first, std::string last){
    std::string name = (first + last);
    //checks to ensure the friend exists in the user's friend list
    if (_friends.count(name.c_str()) == 1){
        _friends.erase(name.c_str());
    }
}

此外,我想这也适用于map::insert()。我只从用std::string打开文件中知道这个用法。任何和所有的建议都非常感谢提前!

不,这里没有理由使用c_str。在使用erase之前,您不需要检查是否存在。你的功能可能很简单:

void Person::removeFriend(const std::string& first, const std::string& last){
    std::string name = (first + last);
    _friends.erase(name);
}

甚至:

void Person::removeFriend(const std::string& first, const std::string& last){
    _friends.erase(first + last);
}

std::map有一个erase的重载,它只占用密钥。

size_type erase( const key_type& key );

您可以简单地使用:

std::string name = (first + last);
_friends.erase(name);