我不知道为什么会出现分段错误。我尝试做素数查找功能。
我创建了向量调用“numbers”,其中包含从 const min 到 const max 的数字以及如果它是素数。它将将该数字的乘法变为 1 并将素数添加到向量名称“p_numbers”中,min 将只是素数,但这并不重要,因为我遇到了分段错误。为什么?
#include <iostream>
#include <vector>
std::vector<int> primes_between(const int unsigned min, const unsigned int max)
{
std::vector <int> numbers;
for (int i=min; i<= max; i++) numbers.push_back(i);
std::vector<int> p_numbers;
auto start = numbers.begin();
auto end = numbers.end();
for (int value : numbers)
{
if (value != 1)
{
p_numbers.push_back(value);
for (auto itr = start+value-min; itr != end; itr += value) *itr = 1;
}
}
return p_numbers;
}
当您使用
push_back()
修改向量时,它会使所有迭代器无效。所以你不能在 begin()
end()start``and
endin
begin() 和 end()`中保存 ; you have to keep calling
。