回溯时出现错误“无法增加值初始化列表迭代器”

时间:2019-09-17 06:18:06

标签: c++ list iterator

我有一个字符列表,范围从['0','9']。我必须对尝试实现回溯的所有可能值(10!)进行置换。我的逻辑是在当前位置设置一个字符,将其从列表中删除,在下一个位置上递归,然后将该字符再次添加回列表中的相同位置。代码可以编译,但是给了我一个运行时错误“调试断言失败!表达式:无法增加值初始化列表迭代器”。

这是我的代码:

#include <iostream>
#include <list>
#include <string>
#include <vector>

using namespace std;

bool isValid(string& s)
{
    vector<int> V{ 2, 3, 5, 7, 11, 13, 17 };
    for (size_t i = 0; i < V.size(); ++i)
        if (stoi(s.substr(i + 1, 3)) % V[i] != 0)
            return false;
    return true;
}

long permuteAndFind(list<char> L, string s)
{
    if (s.size() == 10)
        if (isValid(s))
            return stol(s);
        else
            return 0;

    long sum = 0;
    for (list<char>::iterator itr = L.begin(); itr != L.end(); ++itr)
    {
        char c = *itr;
        list<char>::iterator pos = L.erase(itr);
        sum += permuteAndFind(L, s + c);
        L.insert(pos, c);
    }
    return sum;
}

int main()
{
    list<char> L{ '0', '1', '2', '3', '4', '5', '6','7', '8', '9' };
    cout << permuteAndFind(L, "") << endl;
}

编辑:正确的代码

#include <iostream>
#include <list>
#include <string>
#include <vector>

using namespace std;

bool isValid(string& s)
{
    vector<int> V{ 2, 3, 5, 7, 11, 13, 17 };
    for (size_t i = 0; i < V.size(); ++i)
        if (stoi(s.substr(i + 1, 3)) % V[i] != 0)
            return false;
    return true;
}

long permuteAndFind(list<char> L, string s)
{
    if (s.size() == 10)
        if (isValid(s))
            return stol(s);
        else
            return 0;

    long sum = 0;
    for (list<char>::iterator itr = L.begin(); itr != L.end();)
    {
        char c = *itr;
        list<char>::iterator pos = L.erase(itr);
        itr = pos;
        sum += permuteAndFind(L, s + c);
        L.insert(pos, c);
    }
    return sum;
}

int main()
{
    list<char> L{ '0', '1', '2', '3', '4', '5', '6','7', '8', '9' };
    cout << permuteAndFind(L, "") << endl;
}

0 个答案:

没有答案