如何判断字符串键是否存在于映射中
How to figure out if the string key exists in a map?
考虑到一个简单的std::map<std::string*,std::string*>
,我想检查映射中是否存在字符串指针的值
我已经尝试过了,但编译器在映射中查找指针本身,而我想检查指向的(实际)值。
int main() {
map<string*,string*> c;
std::string a("dude");
std::string* b=new string("dude");
std::string* ap;
c.insert(std::make_pair<string*,string*>(&a,&a));
for( map<string*, string*>::iterator ii=c.begin(); ii!=c.end(); ++ii){
ap=(*ii).first;
if(ap->compare(*b)){
cout<<"Yeah, dude has been foundn";
}
}
if(c.find(b)==c.end()){
cout<<"No dude!n";//wrong!
}
if(c.count(b)==0){//how to find out if there is dude string?
cout<<"No dude dude!n";//wrong!
}else{
cout<<"Yeah, dude has been foundn";
}
return 0;
}
一般来说,我有两个字符串指针,我想比较这些字符串。我该怎么做
提前谢谢。
你不能真正使用指针作为键,除非你真的希望指针是键,而不是它指向的。
指针&a
和指针b
不同,这就是为什么找不到键的原因。
使用普通(非指针)std::string
作为键,它应该会更好地工作。
如果经过仔细测量和考虑,您仍然确定不能接受复制std::string
s,并且可以保证string
s与地图一样长,请考虑以下方法。不要仅仅因为使用它们。
最简单的方法就是使用std::reference_wrapper<T>
。它与原始指针具有相同的语义,只是对引用的对象执行比较/哈希等操作
Chnossos刚刚提到了那个有用的标准库成员。
在这一点之后留下我以前的答案,因为它们允许更多的定制。
添加您自己的struct wrapped_pointer{std::string* x}
,并专门设计比较器std::less
来考虑指向字符串。
通过为std::map
的第三个模板自变量提供显式自变量,可以实现大致相同的结果。
如果您提供一个自定义函数/函子来比较两个string*
s,您可以随心所欲。
这是一个如你所想的那样有效的版本:
#include <map>
#include <iostream>
#include <string>
using namespace std;
// Define a functor class to compare two string* objects.
struct string_less
{
bool operator()(string* lhs, string* rhs) const
{
return (lhs->compare(*rhs) < 0);
}
};
int main() {
// Use string_less while constructing the map.
map<string*,string*, string_less> c;
std::string a("dude");
std::string* b=new string("dude");
std::string* ap;
c.insert(std::make_pair<string*,string*>(&a,&a));
for( map<string*, string*, string_less>::iterator ii=c.begin(); ii!=c.end(); ++ii){
ap=(*ii).first;
// This was another line that needed to be fixed.
if(ap->compare(*b) == 0 ){
cout<<"Yeah, dude has been foundn";
}
}
if(c.find(b)==c.end()){
cout<<"No dude!n";//wrong!
}
if(c.count(b)==0){//how to find out if there is dude string?
cout<<"No dude dude!n";//wrong!
}else{
cout<<"Yeah, dude has been foundn";
}
return 0;
}
在我的机器上运行程序的输出:
是的,伙计被找到了是的,伙计被找到了
相关文章:
- 为什么我的变量存在于其范围之外
- C++ 删除存在于另一个矢量中的矢量项,同时保留顺序
- CPP 使用不存在的键访问映射
- 在功能块中使用新运算符时存在于堆或堆栈上?
- "new"创建的实例的所有成员变量是否都存在于堆上而不是堆栈上?
- 擦除映射 c++ 中其他键的值中已存在的那些值
- 如何检查映射值中是否存在元素
- 由于相同的文件名/类名存在于不同的SO中而导致的SEG错误
- 当键不存在时,映射给出的值
- 检查元素是否存在于二维矢量中
- 有效地检查映射 c++ 中是否存在元素
- 在另一个对象 B 中创建对象 A 时,对象 A 是否是对象 B 的本地对象,对象 A 是否会存在于对象 B 的实例化之外?
- 如何使用type_traits生成依赖于是否存在类专用化的代码?
- 适用于预先存在的类层次结构的函数的最佳模式
- 如何从映射中修改键值对的值,而我不知道该键是否存在于映射中
- 检查元素是否存在于映射中的映射中
- Python支持排序字典 - 类似于C++映射
- java库类似于c++映射
- 我在多映射中得到了两次相同的密钥,它只存在于文本文件中
- 如何判断字符串键是否存在于映射中