程序似乎在for循环 - C ++之后静默终止

问题描述 投票:-4回答:1

我创建了一个程序,打印出通过命令行参数提供的字符的所有排列,并决定将执行时间与用Java编写的等效程序进行比较。

该程序一直有效,直到我决定多次找到排列以获得平均执行时间。

void avgTime(char**& argv, int times) {
    if (sizeof(argv) > 1) {

        long permutationAmnt;

        clock_t s_start, s_end, t_start, t_end;
        float s_runms, t_runms;

        long avg_time;

        for (int count = 0; count < times; count++) {

            t_start = clock();

            for (int i = 1; i < sizeof(argv); i++) {
                s_start = clock();
                permutationAmnt = permutations(std::string(argv[i]));
                s_end = clock();

                s_runms = ((float)s_end - s_start) / CLOCKS_PER_SEC * 1000;
                std::cout << "SUCCESS (" << s_runms << "ms for " << permutationAmnt << " permutations)" << std::endl << std::endl;
            }

            t_end = clock();

            t_runms = ((float) t_end - t_start) / CLOCKS_PER_SEC * 1000;
            std::cout << std::endl << "TOTAL RUNTIME: " << t_runms << "ms" << std::endl;
            avg_time += t_runms;
        }

        std::cout << "AVERAGE RUNTIME: " << avg_time / times << "ms" << std::endl;
    }
}

int main(int argc, char** argv) {
    avgTime(argv, 10);
    return 0;
}

avgTime()中的第一个for循环只执行一次(将一个cout放在其中只打印一次),程序似乎在嵌套的for循环中断后终止。

我不确定问题是来自avgTime()的一些代码,还是来自其中一个辅助函数,如permute()。这里的任何一种方法都是每个辅助函数以及包含的代码(p.s.num在任何函数之外声明)。

/*
* Calls the recursive permute() function then
* returns the total amount of permutations possible
* for the given input.
*
* NOTE: the num variable is used in the permute() function
* for numbering the permutations printed as output (see next function
* for clarificiation)
*/
long permutations(const std::string& arg) {
    long totalPermutations = factorial(arg.size()); //self-explanatory

    num = 1;
    permute(arg, 0);

    return totalPermutations;
}


/*
 * Recursively prints out each permutation
 * of the characters in the argument, str
 */
void permute(const std::string& str, int place) {
    if (place == str.size() - 1) std::cout << ((num <= 10) ? "0" : "") << num++ << ". " << str << std::endl;

    for (int i = place; i < str.size(); i++) {
        permute(swap(place, i, str), place + 1); //self-explanatory
    }
}

long factorial(int num) {
    if (num < 2) {
        return 1;
    }
    return factorial(num - 1) * num;
}

std::string swap(int i, int j, const std::string& str) {
    std::string s(str);
    s[i] = s[j];
    s[j] = str[i];
    return s;
}

注意:permute()函数出现在源代码中的permutation()函数之前,并且对于它的所有必要调用者都是可见的。

//Includes and namespace stuff
#include <iostream>
#include <string>
#include <time.h>

如果您希望我提供任何其他信息,我将非常感谢您提供的任何帮助。再次感谢任何帮助。

附:不,这不是家庭作业:P

编辑:删除using namespace std;并相应调整代码,以避免功能std::swap()和我自己的swap()函数之间的混淆。此外,添加了swap()factorial()函数以避免任何歧义。我为这引起的混乱道歉。

c++ loops for-loop recursion execution
1个回答
0
投票

我使用sizeof(argv)而不是仅仅使用argc。切换到后一个选项可以解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.