Reputation: 45
So I'm trying this little exercise to the get the hang of c++, the problem is that whenever I use an iterator for the vector that contains the results, it always starts at the end of the vector then crashes.
cin >> mTestCases;
int i = 0;
while (mCycles.size() < mTestCases) {
int x;
cin >> x;
mCycles.push_back(x);
}
//Cycling through said values
vector<int>::iterator iterator;
i = 0;
for(iterator = mCycles.begin(); iterator != mCycles.end(); ++iterator) {
int j = 0;
int height = 1;
while (j < *iterator) {
if (j%2)
height++;
else
height*=2;
j++;
}
mResults.push_back(height);
}
vector<int>::iterator resultsIterator;
for (resultsIterator = mResults.begin(); resultsIterator != mResults.end(); ++resultsIterator) {
cout<<mResults.at(*resultsIterator)<<endl;
}
The turd code in question is this for loop above this text right here. For some reason if I enter in 3 test cases, I'll get 3 results placed into the vector, so resultsIterator starts at the very last value, it gets printed out, and then boom crashes, because it's trying to access outside of the vector.
Upvotes: 1
Views: 96