我想在条件表达式中定义变量,以便变量范围在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
之间有什么区别?
答案 0 :(得分:5)
在这方面,int *
和map::iterator
之间没有区别。您使用int *
和map::iterator
的周围语义结构存在差异,这就是为什么编译而其他语句不编译的原因。
使用if
,您可以选择
if (declaration)
或
if (expression)
宣言不是表达。您不能在较大的表达式中将声明用作子表达式。您不能将声明用作显式比较的一部分,这正是您尝试执行的操作。
例如,如果您尝试使用int *
做同样的事情,就像这样
if ((int* x = new int(123)) != NULL)
代码不会因为map::iterator
代码无法编译的原因完全相同而无法编译。
你必须使用
if (int* x = new int(123))
或
int* x = new int(123);
if (x != NULL)
或
int* x;
if ((x = new int(123)) != NULL)
如您所见,int *
表现出与map::iterator
完全相同的行为。
在您的示例中,无法声明it
并在props.end()
条件下与if
进行比较。您将不得不使用上述变体之一,即
map<string, Property>::iterator it = props.find(PROP_NAME);
if (it != props.end())
或
map<string, Property>::iterator it;
if ((it = props.find(PROP_NAME)) != props.end())
选择您喜欢的更多。
P.S。当然,正式你也可以写
if (map<string, Property>::iterator it = props.find(PROP_NAME))
但它没有做你想做的事情(不会将迭代器值与props.end()
进行比较)并且可能根本不编译,因为迭代器类型可能无法转换为bool
。
答案 1 :(得分:1)
以下是将其限制为范围的一种方法:
{
auto it = props.find(PROP_NAME);
if (it != props.end()) {
it->do_something();
}
}
当然,这个范围在技术上并不是“if范围”,但应该同样适用于所有实际意图和目的。
作为AndreyT already explained(+1),声明不能超越(
和)
,你没有用于int
,但是你为迭代器做过。< / p>
答案 2 :(得分:0)
映射迭代器包含first
和second
,它们分别指向键和值。
要访问该值的成员,请使用it->second.do_Something()