2012-11-07 49 views
3

我想知道是否有某種類型的迭代器可以迭代std :: string中的值,從開始到結束時從頭開始。換句話說,這個對象會無限地迭代,一遍又一遍地吐出相同的值序列。是否有類似於循環迭代器的循環?

謝謝!

+0

升壓有類似的東西。 – chris

+0

檢查這個答案http://stackoverflow.com/a/1782262/1762344 –

+1

@Evgeny該答案中的增量()函數看起來可疑。如果推進結束,它應該立即跳回來開始。 – Yakk

回答

5

生成器函數可以是。升壓迭代器具有迭代器適配器:

樣本:http://coliru.stacked-crooked.com/a/267279405be9289d

#include <iostream> 
#include <functional> 
#include <algorithm> 
#include <iterator> 
#include <boost/generator_iterator.hpp> 

int main() 
{ 
    const std::string data = "hello"; 
    auto curr = data.end(); 

    std::function<char()> gen = [curr,data]() mutable -> char 
    { 
     if (curr==data.end()) 
      curr = data.begin(); 
     return *curr++; 
    }; 

    auto it = boost::make_generator_iterator(gen); 
    std::copy_n(it, 35, std::ostream_iterator<char>(std::cout, ";")); 
} 
+0

添加了_short_示例(同樣在[LWS]上使用'copy_n'(http://liveworkspace.org/代碼/ 2e09ce186cca5785742f7d7b25c005d0)) – sehe