我嘗試的項目歐拉問題之一,第一個它要你計算的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