什么是begin()== end()?

时间:2016-05-29 03:13:13

标签: c++ arrays c++11

array.zero-2说:

  

如果N == 0begin() == end() ==唯一值。该   返回值data()未指定。

这个独特的价值是什么意思?这是否意味着表达式begin() == end()的结果是唯一值?我没有看到这有什么意义,因为布尔只能是真或假,这不是很独特。我运行了以下测试:

#include <array>
#include <iostream>
#include <iomanip>
#include <type_traits>

int main()
{
    std::array<int, 0> test;
    auto b = test.begin();
    auto e = test.end();
    std::cout << std::boolalpha 
              << (test.begin() == test.end())
              << std::is_same<bool, decltype(test.begin() == test.end())>::value
              << std::is_same<bool, decltype(b == e)>::value;
}

这一切都按预期输出true。然后我想知道对于非零大小的数组可能会有所不同:

int main()
{
    std::array<int, 0> test;
    std::array<int, 1> test2;
    std::cout << std::boolalpha
              << std::is_same<
                    decltype(test.begin() == test.end()),
                    decltype(test2.begin() == test2.end())
                >::value
              << std::is_same<
                    decltype(test.begin()),
                    decltype(test2.begin())
                >::value;
}

再一次都是真的。那么“独特价值”是什么意思呢?什么有独特的价值?

2 个答案:

答案 0 :(得分:6)

begin() == end() == unique value更像是一个逻辑描述而不是实际的C ++。它声明begin()与end()相同,并且它们都等于某个唯一值。

基本上是逻辑表达式'a = b = c',除了使用C ++ ==

答案 1 :(得分:3)

begin()==end()==unique value是标准eze简写,而不是C ++表达式。

这只是意味着可以在不导致未定义行为的情况下评估begin()end(),并且可以比较它们的相等性。要为零元素数组执行此操作,它们需要提供有效(可比较)的值,即使该值无法解除引用(用于访问数组元素或该类型的任何变量 - 这是{{1 }})。

如果他们用更多的话来说,那可能会更容易,但这就是生命。很多人为了简洁而易于理解。写这篇文章的人可能会像数学家一样思考,但觉得他们必须使用C ++语法。