如何通过它们在向量中的位置来比较两个值的条件

时间:2015-03-24 09:31:11

标签: c++ vector

sort(stor);
    for (int i = 0; i < stor.size(); ++i){
        if (i != 0 && stor[i] == stor[i - 1]){ // is stor[i] a repeat?
            if (repCheck[repCheck.size() - 1] == stor[i]){ // do we already know about this repeat? *program crashes when reaching this line*
                ++repCount[repCount.size() - 1]; // increment the last value in repCount
            }
            else {
                repCheck.push_back(stor[i]); // store this new repeat at the end of repCheck
                repCount.push_back(1); // start a new count for repetitions at the end of repCount
            }

        }
    }

程序在到达第二个if语句时崩溃了,试图以这种方式比较值有什么本质错误吗?编辑:对于错误消息的混淆。

1 个答案:

答案 0 :(得分:0)

如果if为0,则第二个repCheck.size()可能会失败。这是您的情况吗?

您可能希望将if (repCheck[repCheck.size() - 1] == stor[i])更改为if (repCheck.size() > 0 && repCheck[repCheck.size() - 1] == stor[i])

请注意,您可以从i = 1开始循环,然后避免第一个i !=0中的测试if