在迭代矢量时移位位置

Bob*_*ohn 0 c++ c++11

如何替换迭代矢量的位置?我尝试过类似的东西:

for(auto x : vect+2)
Run Code Online (Sandbox Code Playgroud)

但这不起作用.我确信这是一个简单的决心,但我无法在网上找到任何东西.

And*_*owl 6

如果要使用基于范围的for,可以使用Boost.Range创建从vector(begin() + 2)的第三个元素开始的范围:

for (auto x : boost::make_iterator_range(begin(v) + 2, end(v)))
{
    std::cout << x << " ";
}
Run Code Online (Sandbox Code Playgroud)

这是一个简单的例子:

#include <iostream>
#include <vector>
#include <algorithm>
#include <boost/range.hpp>
#include <boost/range/adaptors.hpp>

int main()
{
    std::vector<int> v(10);
    iota(begin(v), end(v), 1);

    for (auto x : boost::make_iterator_range(begin(v) + 2, end(v)))
    {
        std::cout << x << " ";
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您想遍历每个第二个元素,您可以更改范围,如下所示:

namespace rng = boost::adaptors;
for (auto x : v | rng::strided(2))
{
    std::cout << x << " ";
}
Run Code Online (Sandbox Code Playgroud)

在完整的程序中将是:

#include <iostream>
#include <vector>
#include <algorithm>
#include <boost/range.hpp>
#include <boost/range/adaptors.hpp>

int main()
{
    namespace rng = boost::adaptors;

    std::vector<int> v(10);
    iota(begin(v), end(v), 1);

    for (auto x : v | rng::strided(2))
    {
        std::cout << x << " ";
    }
}
Run Code Online (Sandbox Code Playgroud)

Boost.Range非常灵活,因此您可以上面的两个适配器组合在一起:

for (auto x : boost::make_iterator_range(begin(v) + 2, end(v)) |
              rng::strided(3))
{
    std::cout << x << " ";
}
Run Code Online (Sandbox Code Playgroud)

如果您不想或不能使用Boost,您可以使用for带迭代器的经典循环:

for (auto i = begin(v) + 2; i != end(v); ++i)
{
    std::cout << *i << " ";
}
Run Code Online (Sandbox Code Playgroud)

这就是整个程序的样子:

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<int> v(10);
    iota(begin(v), end(v), 1);

    for (auto i = begin(v) + 2; i != end(v); ++i)
    {
        std::cout << *i << " ";
    }
}
Run Code Online (Sandbox Code Playgroud)