= container.end()是设计错误/功能还是仅仅是必需? [英] Is it!=container.end() design mistake/feature or just necessity?

查看:72
本文介绍了= container.end()是设计错误/功能还是仅仅是必需?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我在考虑,如果迭代器隐式转换为bool,那么您可以做到

recently I was thinking about how it would be nice if iterators implicitly converted to bool so you could do

auto it = find(begin(x),end(x), 42);
if (it)  //not it!=x.end();
{
}

,但考虑到这一点,我意识到这将意味着必须将it设置为"NULL",这样,如果您想对它进行某些操作,就不能直接使用它(您必须使用x.end()),或者您可以使用它,但是迭代器的大小必须更大(要存储是否指向.end()). 所以我的问题是:

but thinking about it I realized that this would mean that either it would had to be set to "NULL", so that you couldnt use the it directly if you want to do something with it (you would have to use x.end()) or you could use it but iter size would have to be bigger(to store if what it points to was .end() or not). So my questions are:

  1. 示例中的语法在不破坏当前代码且不增加迭代器大小的情况下是否可以实现?
  2. 隐式转换为bool会引起一些问题吗?

推荐答案

您正在假设迭代器是访问容器的一种方式.它们允许您执行此操作,但是它们还允许执行许多显然不适合您期望的操作的事情:

You are working on the assumption that iterators are a way of accessing a container. They allow you to do that, but they also allow many more things that would clearly not fit your intended operations:

auto it = std::find(std::begin(x), std::next(std::begin(x),10), 42 );
    // Is 42 among the first 10 elements of 'x'?

auto it = std::find(std::istream_iterator<int>(std::cout),
                    std::istream_iterator<int>(), 42 );
    // Is 42 one of the numbers from standard input?

在第一种情况下,迭代器确实引用了一个容器,但是您发现的 range 并未包围整个容器,因此无法针对end(x)测试it.在第二种情况下,根本没有容器.

In the first case the iterator does refer to a container, but the range where you are finding does not enclose the whole container, so it cannot be tested against end(x). In the second case there is no container at all.

请注意,针对许多容器的迭代器的有效实现仅包含一个指针,因此任何其他状态都会增加迭代器的大小.

Note that an efficient implementation of an iterator for many containers holds just a pointer, so any other state would increase the size of the iterator.

关于向任何类型bool的转换,它们确实会引起很多问题,但是可以通过explicit转换在C ++ 11中或在C ++中规避它们03通过使用 safe-bool 习惯用语.

Regarding conversions to any-type or bool, they do cause many problems, but they can be circumvented in C++11 by means of explicit conversions, or in C++03 by using the safe-bool idiom.

您可能对另一个概念更感兴趣:范围.范围有多种方法,因此尚不清楚确切的语义应该是什么.我想到的头两个是Boost.Iterator和我最近读过的Alexandrescu的文章关于迭代.

You are probably more interested on a different concept: ranges. There are multiple approaches to ranges, so it is not so clear what the precise semantics should be. The first two that come to mind are Boost.Iterator and an article by Alexandrescu I read recently called On Iteration.

这篇关于= container.end()是设计错误/功能还是仅仅是必需?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆