使用 nullptr 而不是结束迭代器 [英] Use nullptr instead of end iterator

查看:34
本文介绍了使用 nullptr 而不是结束迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用 nullptr 或某种通用的结束迭代器.

I would like to know if it is possible to use nullptr or some kind of generic end iterator.

例如:

// a.b->cdef().g->bdf() is a std::map<int, int>
std::unordered_map<int, int> copy(a.b->cdef().g->bdf().begin(), a.b->cdef().g->bdf().end());

是您通常编写的用于指定开始和结束以初始化新地图的内容.

is what you would normally write to specify the begin and end to initialize the new map.

如果我只想复制整个地图,为什么需要指定结束标记.

Why do I need to specify the end tag if I just want to copy the whole map.

我更喜欢:

std::unordered_map<int, int> copy(a.b->cdef().g->bdf().begin(), nullptr);

std::unordered_map<int, int> copy(a.b->cdef().g->bdf().begin());

std::unordered_map<int, int> copy(a.b->cdef().g->bdf().begin(), std::unordered_map::end);

edit:我从 std::list 更改了示例.到 std::unordered_map.没有从 std::map 到 std::unordered_map 的复制构造函数.

edit: I changed the example from a std::list<int> to a std::unordered_map<int, int>. There is no copy constructor from std::map to std::unordered_map.

推荐答案

回答问题是否可以使用 nullptr 代替 end()?"

To answer the question asked, "Is it possible to use nullptr instead of end()?"

没有

请考虑容器和迭代器是如何实现的.容器知道它的开始和结束迭代器.迭代器知道如何递增、递减以及与另一个迭代器进行比较.

Please think about how the containers and iterators are implemented. A container knows its begin and end iterators. An iterator knows how to increment, decrement and compare itself to another iterator.

以向量为例.开始迭代器如何知道在哪里停止递增?iter == nullptr 如何知道何时返回 true 以便停止?

So take a vector for example. How does the begin iterator know where to stop incrementing? How would iter == nullptr know when to return true so it could stop?

或者取一个循环链表.它没有真正的终点.只有当迭代器再次等于开始迭代器时它才会停止.nullptr 甚至意味着什么?

Or take a circular linked list. It has no real end. It only stops when an iterator equals the begin iterator again. What would nullptr even mean as an end there?

如果你考虑一下实现,你就会明白为什么答案是不".

If you think about the implementation you'll see why the answer is "No."

这篇关于使用 nullptr 而不是结束迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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