【问题标题】:C++: looping over a string - iterator?C ++:循环字符串 - 迭代器?
【发布时间】:2015-07-04 08:03:57
【问题描述】:

让我们假设我有不同的函数访问单个字符串str(获取它的单个字符),并且我想在每次访问时循环遍历这个字符串...我该如何实现呢?

例如:

string str = "abc";
function1(); // returns "a"
function2(); // returns "b"
function3(); // returns "c"
function4(); // returns "a" again
function2(); // returns "b" again
...

所以基本上我有不同的函数访问这个字符串str,如果到达str 的结尾,我需要某种迭代器返回str 的第一个字符。

【问题讨论】:

  • 所以做这样的迭代器。究竟是什么问题?

标签: c++ string loops c++11 iterator


【解决方案1】:

如果您真的想使用迭代器而不是索引,则可以使用 cyclic_iterator,如下所示:

#ifndef CYCLIC_ITERATOR_H_INC_
#define CYCLIC_ITERATOR_H_INC_
#include <iterator>

template <class FwdIt>
class cyclic_iterator_t : public std::iterator<std::input_iterator_tag, typename FwdIt::value_type> {
    FwdIt begin;
    FwdIt end;
    FwdIt current;
public:
    cyclic_iterator_t(FwdIt begin, FwdIt end) : begin(begin), end(end), current(begin) {}

    cyclic_iterator_t operator++() { 
        if (++current == end) 
            current = begin; 
        return *this; 
    }
    typename FwdIt::value_type operator *() const { return *current; }
};

template <class Container>
cyclic_iterator_t<typename Container::iterator> cyclic_iterator(Container &c) { 
    return cyclic_iterator_t<typename Container::iterator>(c.begin(), c.end());
}

#endif

这对于迭代器来说是非常小的——例如,它目前只支持前增量,而不是后增量(它是一个前向迭代器,所以你可以对迭代器做的所有事情就是递增它并取消引用它) .

不过,对于您设想的工作,这似乎已经足够了。

【讨论】:

  • 谢谢,这似乎可以完成这项工作:)
【解决方案2】:

我会使用 % 模数运算符索引出 string。这将为您提供所需的环绕行为。

#include <iostream>
#include <string>

int main()
{
    std::string str = "abc";
    for (int i = 0; i < 10; ++i)
    {
        std::cout << str[i % str.size()] << " ";
    }
}

Output

a b c a b c a b c a

【讨论】:

  • 是的......但问题是没有单个for循环遍历字符串,而是不同的函数做一些事情并访问字符串。你会建议一个“全局”索引,以便调用的每个函数都执行类似str[globalindex % str.size()] 的操作吗?
  • 这真的取决于你的程序的结构。我不确定function1function2 等是如何相关的。它们是类方法吗?你能解释一下你的总体目标是什么吗?
  • 它是密码分析控制台工具的一部分...这些功能不相关(无论是在类中还是在语义上)。
【解决方案3】:

我不知道你需要这个工作多少次,但你在这里(你可以编辑它以适应你的需要):

#include <iostream>
#include <string>

int main()
{
   std::string str = "abc";

    bool bAgain = true;

    int Max = str.length() + 1;

    for(int i = 0; i < Max; i++)
    {
        std::cout << str[i] << "\n";

        if(bAgain)
        {
            if(i == Max - 1)
            {
                i = -1;
                bAgain = false;
                continue;
            }
        }
    }
}

`

Output

 a 
 b 
 c 
 a 
 b 
 c 

【讨论】:

    猜你喜欢
    • 2011-07-22
    • 2023-03-15
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    相关资源
    最近更新 更多