2016-11-11 56 views
1

具有低于对象reverse_iterator的行为[]

// #1 Outputs NOTHING, expected "jihgfedcba" 
for (auto begin = std::rbegin(a), end = std::rend(a); begin != end; ++begin) 
    std::cout << *begin; 
std::cout << std::endl; 
// #2 Outputs "jihgfedcba", as expected 
for (auto begin = std::rbegin(s), end = std::rend(s); begin != end; ++begin) 
    std::cout << *begin; 
std::cout << std::endl; 

但是打印字符输出的阵列打印字符串时没有任何内容显示预期的输出。

打印字符数组也会影响字符串的打印:如果在#2之前写入#1循环,则程序只输出一个字符,但会显示单个jihgfedcba


我注意到,调整的std::rbegin(a)修复问题的返回值:

// Outputs "jihgfedcba", as expected 
// notice the ++!! 
for (auto begin = ++std::rbegin(a), end = std::rend(a); begin != end; ++begin) 
    std::cout << *begin; 
std::cout << std::endl; 

// Outputs "jihgfedcba", as expected 
for (auto begin = std::rbegin(s), end = std::rend(s); begin != end; ++begin) 
    std::cout << *begin; 
std::cout << std::endl; 

这究竟是为什么?

+0

我无法复制。两个循环都为我产生相同的结果。除了const char []之外,前面还有一个额外的空白空间(最有可能是'\ 0')。 – DeiDei

+0

@DeiDei让我给你提供一个[代码](http://melpon.org/wandbox/permlink/k1RqUEKvVRxedJVf),它显示了所描述的行为。 –

回答

1

char阵列包含:

{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', '\0'} // 11 characters 

虽然std::string包含:

"abcdefghij" // 10 characters 

在第一种情况中,最后一个字符(第一循环中)是 '\ 0'。当你“调整”循环时,你跳过这个字符。

即使我无法重现您的行为,我希望这是问题的根源。

+0

这解释了*问题*的一部分。但这并不能解释为什么打印(不调整)'char'数组会阻止控制台中的任何后续输出。 –

+0

我无法重现这一点。在我的情况下,即使没有调整,它也能正确打印。你使用哪个控制台? –

+0

我用最后一个gcc和clang编译器在[Wandbox控制台](http://melpon.org/wandbox/permlink/k1RqUEKvVRxedJVf)中观察到了这种行为。 –

相关问题