cpp向量用于循环终止条件错误

pow*_*est 3 c++ c++11

编译以下函数时,以下是编译错误.为什么yt != endIx在第二轮for循环非法.

错误C2678:二进制'!=':找不到运算符,它接受类型为'std :: _ Vector_iterator >>'的左手操作数(或者没有可接受的转换)

void printDebug(vector <int>  ar)
{
    for (auto it = ar.begin(); it != ar.end(); it++)
    {
        auto endIx = ar.end() - it;
        for (auto yt = ar.begin(); yt != endIx ; yt++)
        {
            cout << *it << " : " << endIx ;
        }
        cout << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

为了避免混淆,我将auto end迭代器重命名为endIx;

qua*_*dev 9

ar.end() - itis 的类型std::vector<int>::difference_type(给出迭代器之间距离类型的容器特征),它不是迭代器.

ar.begin() + end在循环中使用迭代器算术:

void printDebug(vector <int>  ar)
{
    for (auto it = ar.begin(); it != ar.end(); it++)
    {
        auto end = ar.end() - it; // end is of type vector <int>::difference_type
        for (auto yt = ar.begin(); yt != ar.begin() + end; yt++)
        {
            cout << *it << " : " << end;
        }
        cout << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:

你应该通过const引用传递向量,而不是通过值:

void printDebug(const vector<int>&  ar)
{
    for (auto it = ar.begin(); it != ar.end(); it++)
    {
        auto end = ar.end() - it; // end is of type vector <int>::difference_type
        for (auto yt = ar.begin(); yt != ar.begin() + end; yt++)
        {
            cout << *it << " : " << end;
        }
        cout << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)