I was trying one of the project euler problems, the first one where it asked you to calculate the sum of all the multiples of 3 and 5 below 1000.
I attempted it and it shows no errors, however when i run it i get a message box with the error:
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
here is the code:
#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;
}
I know there is a much easier way to do that problem, however i am still learning c++ and wanted to try and use some of the things i had recently learnt.
std::vector<T>::erasewill return you an iterator following the last removed element. If you remove the last element, the returned iterator will beend(). And then you increment the iterator and get an exception. Also, even if you don’t delete the last entry but another, you will still ignore the following element.By the way, what do you want to achieve with
five[*it]? The iterator acts like a pointer to a given element in the container. Either use a simple for-loop with anint iandfive[i](which will have the same problems I stated above) or*it.*Try the following code instead:
* While it’s true that the value of your iterator is its own key this will only last until you first changed the vector. So after your very first erase
five[*it] != *it.