我尝试的项目欧拉问题之一,第一个它要你计算的3所有倍数之和5低于1000 我尝试它,它没有显示出错误,但是当我运行它,我得到一个消息框出现错误:矢量标超出范围的错误消息的
Microsoft Visual C++ Debug Library
Debug Assertion Failed!
Program: ...\c++ learning\project euler ex 1\Debug\project euler ex 1.exe
File: c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\vector
Line: 932
Expression: vector subscript out of range
For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.
(Press Retry to debug the application)
Abort Retry Ignore
这里是代码:
#include <iostream>
#include <vector>
#include <numeric>
using std::endl; using std::cout;
using std::vector;
int main()
{
vector<int> five;
vector<int> three;
int x;
int y;
int sum;
for(int i = 0; i < 1000; i = i + 5)
{
five.push_back(i);
}
for(int i = 0; i < 1000; i = i + 3)
{
three.push_back(i);
}
for(vector<int>::iterator it = five.begin(); it != five.end(); ++it)
{
if (five[*it] % 3 == 0)
{
it = five.erase(it);
}
}
for(vector<int>::iterator it = three.begin(); it != three.end(); ++it)
{
if (three[*it] % 5 == 0)
{
it = three.erase(it);
}
}
x = accumulate(five.begin(), five.end(), 0);
cout << x << endl;
y = accumulate(three.begin(), three.end(), 0);
cout << y << endl;
sum = x + y;
cout << sum << endl;
system("PAUSE");
return 0;
}
我知道有一个更简单的方法来做到这一点的问题,但是我我仍然在学习C++,并想尝试使用我最近学习的一些东西吨。
开始从最终循环的载体,而不是开始。 – user15 2012-08-04 15:51:25
永远不要修改你迭代的集合。 – 2012-08-04 15:53:56