简体   繁体   中英

How do I get the previous element of a list using the same iterator?

I am making a Sudoku solver and I cannot manage to get backtracking working by refering to the last element of my list (which holds the positions of the blank spaces).

The code below shows my naive initial approach to this issue:

void solve(int arr[9][9])
{
    position CurrentPos;

    list<position>::iterator j;
    for (j = blankSpaces.begin();  j != blankSpaces.end();  j++)
    {
        CurrentPos.row = j->row;
        CurrentPos.col = j->col;

        for (int i = arr[CurrentPos.row][CurrentPos.col] + 1; i < 10; i++)
        {
            if (valid(arr, CurrentPos, i))
            {
                arr[CurrentPos.row][CurrentPos.col] = i;
                visitedStack.emplace_front(CurrentPos);
            }
            if (!(valid(arr, CurrentPos, i)) && (i == 9))
            {
                j--;
            }
        }
    }

}

You can get the last element of the list by doing the following:

#include <iostream>
#include <iterator>
#include <list>

int main () {
    std::list<int> mylist;
    for (int i = 0; i < 10; i++)
        mylist.push_back (i*10);

    auto last = std::prev(mylist.end());
    std::cout << "The last element is " << *last << '\n';

    return 0;
}

Or you can get the iterator before another iterator by using the same like this:

#include <iostream>
#include <iterator>
#include <list>

int main () {
    std::list<int> mylist;
    for (int i = 0; i < 10; i++)
        mylist.push_back (i*10);

    auto last = std::prev(mylist.end());
    auto prelast = std::prev(last);
    std::cout << "The last element is " << *last << '\n';
    std::cout << "The prelast element is " << *prelast << '\n';

    return 0;
}

Or just use -- as you already do:

#include <iostream>
#include <iterator>
#include <list>

int main () {
    std::list<int> mylist;
    for (int i = 0; i < 10; i++)
        mylist.push_back (i*10);

    auto last = std::prev(mylist.end());
    auto prelast = std::prev(last);
    std::cout << "The last element is " << *last << '\n';
    std::cout << "The prelast element is " << *prelast << '\n';

    prelast--;
    std::cout << "The preprelast element is " << *prelast << '\n';

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM