Полагаю, вы сами решили проблему прямо сейчас. Но в любом случае, давайте ответим на вопрос так, чтобы это не было счетом с 0 ответами.
Ошибка в этой строке:
// maxIndex will be the idex at maxValue or address
maxIndex = maxValues[i];
Вы сохраняете не индекс, а значение , И это может быть большим значением и, следовательно, вне пределов.
Правильное решение:
// maxIndex will be the idex at maxValue or address
maxIndex = i;
Это должно сработать.
Просто ради удовольствия Я создал «более современные C ++» - элементы решения с использованием библиотеки алгоритмов. Пожалуйста, смотрите:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
// Collatz Sequence and its max value
struct CollatzSequence {
CollatzSequence() {}
// This will construct the collatez sequence and calculate the max value
explicit CollatzSequence(unsigned int value);
// Values of the Collatz Sequence
std::vector<unsigned int> data{};
// The maximum value of all values of the Collatz sequence
unsigned int maxValue{ 1U };
};
// Constructor for the Collatz Sequence. Will calculate all values of the sequence and the maxim value
CollatzSequence::CollatzSequence(unsigned int value) {
// We calculate values as long as we did not find 1, always the last vale
// (There is no mathematicla evidence that this is always true)
while (value > 1U) {
// Store the current calculated value
data.push_back(value);
// Check, if this is the biggest value so far, and, if so, store it
maxValue = std::max(value, maxValue);
// Calculate next value in the row according to the Collatz Sequence rules
value = ((value & 1U) == 0) ? (value >> 1U) : (3U * value + 1U);
}
// Always add 1 as the last element. This we do not need to calculate
data.push_back(1U);
}
int main() {
// Inform user to enter start end end value
std::cout << "Calculate Collatz sequences. Please specify a range, a start and a end value:\n";
// Read the start value and check, if this worked
if (unsigned int rangeStart{}; std::cin >> rangeStart) {
// Now read end value and check, if a correct range has been specified
if (unsigned int rangeEnd{}; (std::cin >> rangeEnd) && rangeStart <= rangeEnd) {
// Create a vector for Collatz Sequences. Allocate sufficent elements for the specified range
std::vector<CollatzSequence> sequences(rangeEnd - rangeStart + 1);
// Create all requested sequences
std::generate(sequences.begin(), sequences.end(), [i = rangeStart]()mutable { return CollatzSequence(i++); });
// Get the max element
std::vector<CollatzSequence>::iterator mve = max_element(sequences.begin(), sequences.end(),
[](const CollatzSequence& cs1, const CollatzSequence& cs2) { return cs1.maxValue < cs2.maxValue; });
// Show result to the world
std::cout << "Max Value: " << mve->maxValue << " (" << mve->data[0] << ")\n";
}
else {
std::cerr << "\n*** Error: Invalid range specified\n";
}
}
else {
std::cerr << "\n*** Error: Could not get start value for range\n ";
}
return 0;
}