如何根据两个值在向量中的位置进行条件比较
How to make a conditional comparing two values by their position in a 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 语句时崩溃,尝试以这种方式比较值是否存在固有错误?编辑:对错误消息的混淆。
如果 repCheck.size()
为 0,第二个 if
可能会失败。这是你的情况吗?
您可能希望将 if (repCheck[repCheck.size() - 1] == stor[i])
更改为 if (repCheck.size() > 0 && repCheck[repCheck.size() - 1] == stor[i])
请注意,您可以从 i = 1
开始循环,然后在第一个 if
中避免测试 i !=0
。
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 语句时崩溃,尝试以这种方式比较值是否存在固有错误?编辑:对错误消息的混淆。
如果 repCheck.size()
为 0,第二个 if
可能会失败。这是你的情况吗?
您可能希望将 if (repCheck[repCheck.size() - 1] == stor[i])
更改为 if (repCheck.size() > 0 && repCheck[repCheck.size() - 1] == stor[i])
请注意,您可以从 i = 1
开始循环,然后在第一个 if
中避免测试 i !=0
。