我创建了一个typedefformap但不能使用该find方法。这是代码:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
typedef std::map<std::string, int> customType;
customType mod;
mod["something"] = 2;
if (mod.find("something"))
{
std::cout << "found";
}
}
Run Code Online (Sandbox Code Playgroud)
对于上面的代码,我收到如下错误:
main.cpp: In function ‘int main()’:
main.cpp:22:17: error: could not convert ‘mod.std::map<_Key, _Tp, _Compare, _Alloc>::find, int, std::less >, std::allocator, int> > >(std::basic_string(((const char*)"something"), std::allocator()))’ from ‘std::map, int>::iterator {aka std::_Rb_tree_iterator, int> >}’ to ‘bool’
if (mod.find("something"))
~~~~~~~~^~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
我知道我可以直接使用std::map而没有,typedef但这段代码只是我想在项目中做的事情的一个例子。请帮助我找到使用该find方法的方法。
这与模板和 typedef 无关。相反,您使用的find方法不正确。的行为find描述如下:
[返回一个] 迭代器,其键等同于键的元素。如果没有找到这样的元素,
end()则返回结尾(参见)迭代器。
要检查键是否存在(即迭代器有效),您可以检查以确保迭代器不等于尾后迭代器:
if (mod.find("something") != mod.end())
Run Code Online (Sandbox Code Playgroud)
在C++20以后,可以直接使用contains成员测试的方法:
if (mod.contains("something"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
50 次 |
| 最近记录: |