第一个单词匹配后退出递归

时间:2016-11-19 04:13:18

标签: c++ recursion

此功能旨在获取拼写错误的单词并对其进行置换,根据单词列表检查每个完整的排列,直到找到匹配为止。

找到匹配后,该函数将终止并立即返回匹配的单词,而不会进一步置换。

在当前状态下,该功能有效,但在所有排列完成之前,它会继续置换并找到匹配项。

函数find()可以被认为是一个黑盒子,如果该单词与dcnV向量中的单词匹配则返回true,如果不匹配则返回false。此功能正常运行。

dcnV:包含字典中单词列表的字符串向量。

pos:递归算法使用的整数。

p []:解决方案数组。

used []:用于跟踪当前使用的索引的数组 排列。

word:从调用函数传入此函数的单词(来自文本文件)。

    string permute ( vector <string> dcnV , int pos , int p [] ,
    int used [] , string & word )
{
    string tgt = word;  //sets tgt to have the same size as word

    unsigned int n = word.size ();  //determines for loop range
    unsigned int i = 0;  //iterator

    /* base case: when the end of the array is reached,
     * map tgt to word using p array indexes
     * search dictionary vector dcnV for matching word
     * if found, return tgt
     */
    if ( pos == n && p [0] == 0 && p [n - 1] == n - 1 )
    {
        for ( i = 0; i < n; i++ )
        {
            tgt [i] = word [p[i]];
        }

        if ( find ( dcnV , tgt ) )
        {
            cout << "\n  Found matching word: " << tgt;
            return tgt;
        }
    }

    // recursive permutation algorithm. this is functioning correctly
    for ( i = 0; i < n; i++ )
    {
        if ( used [i] == 0 )
        {
            p [pos] = i;
            used [i] = 1;
            permute ( dcnV , pos + 1 , p , used , word );
            used [i] = 0;
        }
    }

    // if end of fn is reached without match, return tgt with '*' appended in
    // front
    return "*" + word;
}

尝试不起作用的解决方案:

使用静态向量来保存匹配的单词,然后只返回此向量的第一个元素。

在找到单词时设置标志,并在函数开头添加逻辑检查,如果设置了标志,则立即返回。

可能不会使用setjmp,longjmp,exit,break和exception。

1 个答案:

答案 0 :(得分:0)

请使用Context context, AppWidgetManager appWidgetManager, int appWidgetId进行编译,或只复制置换功能

-std=c++11