更简单、更便携的方式来迭代所有字符值?



对于我正在教的一堂课,我需要编写一段代码来迭代所有可能的char值。我想以一种可以在不同C++实现中移植的方式做到这一点。这意味着

  • 我不能假设charsignedunsigned
  • 我不能假设char是八位,
  • 我不能假设sizeof(int) > 1
  • 我不能假设int32_t等类型存在,
  • 我不能假设整数溢出不会捕获,
  • 等。

我想出的最佳解决方案是以下不寻常的do ... while循环:

char ch = numeric_limits<char>::min();
process(ch);
do {
ch++;
process(ch);
} while (ch != numeric_limits<char>::max());

这种方法有效,但对我来说感觉很笨拙。直觉上可能需要这样的方法是有道理的,因为增量数比可能的字符数多 1,但也许有一种根本不同的方法可用,更接近传统的for循环。

有没有一种便携式方法可以实现这一点,比这更笨重?

但也许有一种根本不同的方法,更接近传统的 for 循环。

好吧,您可以使用实际的for循环:

#include <limits>
#include <iostream>
void process(char ch)
{
std::cout << static_cast<long>(ch) << ' ';
}
int main()
{
for ( char ch = std::numeric_limits<char>::min(); ; ++ch )
{
process(ch);
if ( ch == std::numeric_limits<char>::max() )
break;
}
std::cout << 'n';
}

您可以创建一个看起来像容器的包装类。

struct Chars {
enum {
Chars_MIN = std::numeric_limits<char>::min(),
Chars_MAX = std::numeric_limits<char>::max()
};
struct Iterator {
char c_;
bool end_;
Iterator (char c, bool e = false) : c_(c), end_(e) {}
auto & operator ++ () {
if (c_ == Chars_MAX) end_ = true;
else ++c_;
return *this;
}
auto operator * () const { return c_; }
auto operator == (const Iterator &other) const {
return c_ == other.c_ && end_ == other.end_;
}
auto operator != (const Iterator &other) const {
return !(*this == other);
}
};
Iterator begin () const { return Iterator(Chars_MIN); }
Iterator end () const { return Iterator(Chars_MAX, true); }
};

然后,您可以使用新式for语法:

Chars ccc;
for (auto x : ccc) {
process(x);
}

最新更新