我正在尝试一个项目 euler 问题,第一个问题是它要求您计算 1000 以下的所有 3 和 5 的倍数之和。我尝试了它,它没有显示任何错误,但是当我运行它时,我收到一条消息错误框:
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++ 并想尝试使用我最近学到的一些东西。