### 无限循环集合

``````std::vector<int> myvect {1, 2, 3, 4};
``````

#### 7 个答案:

``````for(;;)   // the standard/traditional way to write "forever"
{
for(auto x : myvect)  // the new way to iterate over a vector
{
//
}
}
``````

``````while ( true )
{
for ( int x : myvect ) std::cout << x << ", ";
}
``````

``````for ( std::vector<int>::size_type i = 0; i < nyvect.size(); i = ( i + 1 ) % myvect.size() )
{
std::cout << x << ", ";
}
``````

``````while (true) {
// iterate myvect
for (int i=0; i<myvect.size(); i++) {
std::cout << myvect[i] << ", ";
}
}
``````

``````index = 0;
while(true)
{
//Access your vector element using index
index = ( index + 1 ) % length;
}
``````

C ++：

``````std::vector<int> myvect {1, 2, 3, 4};
std::vector<int>::iterator vecIter = myvect.begin();
while(1){
for(vecIter = myvect.begin();vecIter != myvect.end();++vecIter){
std::cout << *vecIter << " " << ;
}

}
``````

C ++ 11X：

``````std::vector<int> myvect {1, 2, 3, 4};
while(1){
for(int i :myvect){
std::cout << i << " " << ;
}

}
``````

``````for(unsigned i=0;true;++i)
do_something( myvect[i%4] );
``````

``````#include <iterator>

template<class Container> class ever_t {
struct iterator {
typename Container::iterator b, e, v;
iterator& operator++() { ++v; if( v == e ) v = b; return *this; };
iterator operator!() { return {b, e, e}; };
bool operator!=(const iterator& o) { return b != o.b || e != o.e || v != o.v; };
typename Container::iterator::reference operator*() { return *v; };
} b;
public:
ever_t(Container& c_) : b{std::begin(c_), std::end(c_), std::begin(c_)} {};
iterator begin() { return b; }
iterator end() { return !b; }
};

template<class Container> ever_t<Container> ever(Container& c) { return ever_t<Container>(c); }

#include <iostream>
#include <vector>

int main() {
std::cout << "oi" << std::endl;
std::vector<int> i { 1, 2, 3, 4 };
std::vector<int> empty;

for( auto x: ever(empty) ) { // never enters here
std::cout << x << std::endl;
}
for( auto x: ever(i) ) {
std::cout << x << std::endl;
}
}
``````