Я создал программу, которая превращает вектор (набор чисел) всех целых чисел от 2 до 100 в список только простых чисел в этом векторе. Это достигается путем удаления чисел из вектора, если они делятся на диапазон чисел, отличных от самих себя.
У меня было много проблем с запуском этого кода без ошибок отладки, и в конечном итоге было установлено, что проблема связано с использованием размера вектора как части условия while l oop. Поскольку удаление чисел из вектора также уменьшило бы размер вектора, моя переменная l oop (j), вероятно, «перепрыгивала» записи в векторе - возможно, из-за этого она пыталась получить доступ к несуществующим векторным размерам.
Решение, которое я нашел, состояло в том, чтобы уменьшить переменную l oop на 1 всякий раз, когда я также уменьшал размер вектора. Однако мне было интересно, есть ли другие способы, которыми вы могли бы решить эту проблему. Спасибо!
#include <iostream>
#include "../../std_lib_facilities.h" // available at http://www.stroustrup.com/Programming/std_lib_facilities.h
#include <vector>
vector<int> numberset;
int j = 0;
int main()
{
bool primetest = true;
// Adding numbers to our list of potential primes (excluding the number 1)
for (int i = 2; i <= 100; i++)
{
numberset.push_back(i);
}
// j represents the current position within the vector numberset
while (j <= numberset.size()-1)
// We're going to look through all the numbers in the vector above, and then divide them by a set of divisors to verify that they're prime. Numbers in the above set that are divisible by a divisor will be removed, since they are not prime.
{
for (int divisor = 2; divisor <= 100; divisor++)
// These are the numbers by which we will divide the vectors
{
//If a certain number within the vector (marked by position j) can be divided a different number >= 2 with a remainder of 0, we know it's not prime.
//We will then set the 'primetest' bool to "false" (indicating that we know this is not a prime number)
if (numberset[j] % divisor == 0 && numberset[j] != divisor)
{
primetest = false;
if (primetest == false)
{
//This line removes the non-prime number from our list of numbers.
numberset.erase(numberset.begin() + j);
//j-- is added in to prevent the code from 'skipping' over numbers in the numberset vector after a number within the vector is removed.
//For example, let's say the third element in the vector (numberset[3]) is 6. If we remove 6 (since it's not prime), the third element then becomes 7, and the 4th element becomes 8.
//However, the j++ below will cause us to next review (numberset[4]), which is 8 rather than 7. Thus the addition of j--, which cancels out the j++ and makes sure we're not skipping elements.
//j++ only runs if a number is erased from the vector, however.
j--;
}
}
}
j++;
}
//This prints out the remaining prime numbers in the vector.
for (int x : numberset)
{
cout << x << " ";
}
}