如何检查密钥是否存在于std :: map中并在if条件下获取map :: iterator?

woo*_*ngs 1 c++

我想在条件表达式中定义变量,以便变量范围在if子句中.这工作正常,

if (int* x = new int(123)) { }

当我试图用map :: iterator做类似的事情时,

if ((map<string, Property>::iterator it = props.find(PROP_NAME)) != props.end()) { it->do_something(); }

我有 error: expected primary-expression before ‘it’

什么区别int*和map::iterator?

AnT*_*AnT 5

这方面int *和map::iterator这方面没有区别.还有周围的语义结构的差异,您使用的是有int *和map::iterator,这就是为什么一个编译和其他没有.

随if你可以选择

if (declaration)
Run Code Online (Sandbox Code Playgroud)

要么

if (expression)
Run Code Online (Sandbox Code Playgroud)

宣言不是表达.您不能在较大的表达式中将声明用作子表达式.您不能将声明用作显式比较的一部分,这正是您尝试执行的操作.

例如,如果你试图做同样的事情int *,就像这样

if ((int* x = new int(123)) != NULL)
Run Code Online (Sandbox Code Playgroud)

代码不会编译因为map::iterator代码无法编译的原因完全相同.

你必须使用

if (int* x = new int(123))
Run Code Online (Sandbox Code Playgroud)

要么

int* x = new int(123);
if (x != NULL)
Run Code Online (Sandbox Code Playgroud)

要么

int* x;
if ((x = new int(123)) != NULL)
Run Code Online (Sandbox Code Playgroud)

如您所见,int *展示的行为完全相同map::iterator.

在您的例子,它是不可能的声明it,并执行与比较props.end()的if病情.您将不得不使用上述变体之一,即

map<string, Property>::iterator it = props.find(PROP_NAME);
if (it != props.end())
Run Code Online (Sandbox Code Playgroud)

要么

map<string, Property>::iterator it;
if ((it = props.find(PROP_NAME)) != props.end())
Run Code Online (Sandbox Code Playgroud)

选择您喜欢的更多.

PS当然,正式你也可以写

if (map<string, Property>::iterator it = props.find(PROP_NAME))
Run Code Online (Sandbox Code Playgroud)

但它没有做你想做的事情(不比较迭代器值props.end())并且可能根本不编译,因为迭代器类型可能无法转换为bool.