使用迭代器作为向量中的位置

Using iterator as position in vector

我正在尝试使用向量编写 Eratosthenes 算法

1) Fill vector with integers 2 to N
2) Find the smallest integer i, print it, delete i, 2i, 3i, etc from vector
3) Repeat 2) until i is greater than square root of N

我是矢量的新手,有点卡在这里:

std::vector<int> x (n-1);

for (int i = 2; i < n+1; i++){     //fill vector with 2 to N
    x[i-2] = i;
}

float nsq = sqrt(n);

//iterate from 2 to sqrt(n):
for (std::vector<int>::iterator current = x.begin(); *current < nsq; current++){ 

    //access positions 0,2,4,6,8 etc in first iteration, 0,3,6,9 in next, etc
    for (int position = current - x.begin(); position <= x.end(); position += *current){
        //print x[position] only in first loop
        //delete x[position]              
    }
}

两个问题:

1) 位置 <= x.end(); returns 一个错误,而且我不能使用 'auto' 因为我没有使用 c++11,尽管我不确定这样做是否有效。解决此问题的最佳方法是什么?

2) 有没有办法在循环开始时只打印一次数字?还是我没有朝着正确的方向前进 algorithm/overcomplicating 呢?

编辑:刚刚意识到我确实把它复杂化了,也感谢您的回答。这是可接受的算法吗?

for (std::vector<int>::iterator current = x.begin(); *current < nsq; current++){

        for (int position = 0; position <= x.size(); position += *current){
            if(position == 0){
                std::cout << x[position] << std::endl;
            }
        //delete x[position]
        }
    }

1) position <= x.end(); returns an error, and I can't use 'auto' since I'm not using c++11 though I'm not sure that'd do the trick. What's the best way to fix this?

迭代器不知道它们在它们正在迭代的容器中的位置。在最基本的层面上,迭代器只是一个可以智能移动的指针;在 std::vector 的情况下,它实际上只是一个指针的包装器。

在此代码中,您将检查索引是否小于或等于指针;你在比较两个完全不同的东西,这没有多大意义。

如果您想知道迭代器在向量中的位置,最好放弃迭代器并只使用索引,而不是试图混合两者。

2) Is there a way to print a number only once at the start of the loop? Or am I not going in the right direction with this algorithm/overcomplicating it?

您可以在第一次迭代中检查 position 是否等于您期望的值,如果匹配则打印数字。

一旦您将一个数字识别为质数,您的意图就是从向量中删除它的所有倍数。好的,这是可能的。但是你不能仅仅推断出所有 5 的倍数(例如)在向量中相差 5 个位置,因为你已经删除了 2 和 3 的倍数,其中一些也是 5 的倍数。实现明智的 @amchacon's上面的建议会容易得多。