简而言之,我试图用C ++编写一个程序,它会提示用户输入初始圈子中的人数,然后告诉他们他们应该站在哪个位置以便在 k (执行前计算的人数)= 3.
我已经得到了我认为正确的想法,但我收到了错误" Debug Assertion Failed"和"表达式:向量擦除迭代器超出范围"如果我将 k 输入为1,2或5以外的任何其他内容。
// ConsoleApplication2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int n;//size of the circle
vector <int> circle; //the circle itself
//ask for how many people are in the circle
cin >> n;
//fill the circle with 1,2,3...n
for (int idx = 0; idx < n; idx++)
{
circle.push_back (idx+1);
}
//cout << "The size of the circle is " << circle.size() << ".\nThe highest number is " << circle[n-1] << "."; //test to make sure numbers are being assigned properly to each vector element
for (int count = 0, idx = 0; circle.size() > 1; idx++,count++)
{
//if the position (idx) is greater than the size of the circle, go back to the beginning of the circle and start counting again
if (idx >= circle.size())
{
idx = 0;
}
//every time the counter reaches three, that person is executed
if (count == 3)
{
circle.erase (circle.begin()+(idx));
count = 0;
}
}
cout << "The place to stand to win the hand is position #" << circle.front() << ".\n";
return 0;
}
答案 0 :(得分:3)
您只需检查if (idx > circle.size())
,然后继续致电circle.erase (circle.begin()+(idx));
。 idx == circle.size()
时,此通话不安全。
答案 1 :(得分:0)
@Pradhan已经为您提供了原始错误的解决方案(idx >= circle.size()
而不是idx >= circle.size()
。
为什么结果仍然不正确:
擦除元素时,必须调整索引以对其进行补偿(减去1)。否则索引对应于向量中的下一个元素,所以实际上你总是每隔4个人执行第3个人。
这是我的代码版本:
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main(){
int n;
cin >> n;
//fill the circle with 1,2,3...n
vector <int> circle(n);
std::iota(std::begin(circle), std::end(circle),1);
int idx = -1;
while (circle.size() > 1) {
//advance by threee
idx = (idx + 3) % circle.size();
//execute Person
circle.erase(circle.begin() + (idx));
//readjust to compensate for missing element
--idx;
}
cout << "The place to stand to win the hand is position #" << circle.front() << ".\n";
}
当然,您可以将循环重写为
int idx = 0;
while (circle.size() > 1) {
//advance by three
idx = (idx + 2) % circle.size();
//execute Person
circle.erase(circle.begin() + (idx));
}