关于地图::擦除和地图::计数
Regarding map::erase and map::count
我只是简单地问了一个关于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);
相关文章:
- 引用一个已擦除类型(void*)的指针
- 擦除while循环中迭代的元素
- 在运行时处理类型擦除的数据-如何不重新发明轮子
- C++擦除(如果存在)
- 在映射擦除c++期间执行循环的次数
- 为什么擦除方法会影响结束方法
- C++ 字符串类擦除成员函数的时空复杂性
- 类型擦除的std::function与虚拟函数调用的开销
- C++14 中unordered_map矢量和擦除删除成语的奇怪行为
- 从地图上擦除元素,然后将其放回原处
- 从地图擦除后访问指针
- 在地图中使用擦除的元素
- 迭代地图和擦除元素
- 如果地图擦除范围内的第一个和最后一个相等,则是否删除该元素
- 如何擦除包含结构的地图 包含结构的地图
- 如何使用结构擦除地图中的值?[C++]
- 地图擦除错误
- 关于地图::擦除和地图::计数
- 如果我引用地图元素C++它不会被擦除
- 安全地从地图内擦除基于的范围