C++ if语句中的反引用
在第一条语句中,C++ if语句中的反引用,c++,if-statement,iterator,dereference,C++,If Statement,Iterator,Dereference,在第一条语句中,it被取消引用为0,因为向量中的元素1是0。在我的第二个if语句中,我想在取消引用它之前增加it int function(vector<int>& vec){ for (auto it = vec.begin() + 1; it != vec.end(); ++it){ if (*it == 0) { cout << "element 1 = 0" << endl;
it
被取消引用为0,因为向量中的元素1是0。在我的第二个if语句中,我想在取消引用它之前增加it
int function(vector<int>& vec){
for (auto it = vec.begin() + 1; it != vec.end(); ++it){
if (*it == 0)
{
cout << "element 1 = 0" << endl;
if (*(it +1) && *(it +2) == 0)
cout << "element 2 and 3 = 0";
return 0;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<int>grid = { 0, 0, 0, 0, 5, 2, 2, 2, 2 };
function(grid);
如果要检查两个元素是否都等于零,则需要使用:
if (*(it +1) == 0 && *(it +2) == 0)
而不是:
if (*(it +1) && *(it +2) == 0)
递增或取消引用迭代器没有问题,因为vector
的迭代器是随机访问的,这允许使用it+n
递增迭代器
您的代码中还有一个问题,增加迭代器可能会超过最后一个元素,这将导致未定义的行为。不清楚您在问什么。抱歉,我已编辑了我的问题。
if (*(it +1) && *(it +2) == 0)