Stack在C ++中是否有迭代器?

时间:2016-07-01 02:31:57

标签: c++

据我所知,堆栈在C ++中没有迭代器。例如,这篇文章(Does std::stack expose iterators?)明确声明堆栈没有迭代器。但是,我的主管告诉我,c ++中的堆栈应该有迭代器,因为它是一个标准的数据结构,你可以做stack.begin()(但是,据我所知,标准C ++中没有这样的语法)。我怎么说服他?为什么堆栈在C ++中没有迭代器?

问题2:谢谢大家的精彩答案。我认为现在的问题归结为:为什么在堆栈中使用迭代器是否有意义?

3 个答案:

答案 0 :(得分:6)

您可以通过建议您的主管去说服您的主管,并阅读ISO / IEC-14882(2011)第23.6.5节,std::stack的规范。

std::stack没有迭代器。

答案 1 :(得分:3)

std::stack提供了底层容器的严格后进先出视图,这就是它的重点:将底层容器的使用限制为LIFO。

因此它不提供迭代。

但是,它确实将底层容器提供为protected成员,这意味着它是为派生而设计的。在派生类中,您可以提供迭代器,以及您想要的任何内容。此外,即使不使用任何强制转换(即通过成员数据指针的隐式转换),也可以只访问普通protected的{​​{1}}成员。

重新添加2 nd 问题,

  

为什么为堆栈设置迭代器没有意义?

这是有道理的,但在大多数情况下,它会提供std::stack旨在删除的非LIFO访问权限,即在大多数情况下,它会与std::stack的目的不一致

对于调试,一个人的调试器将显示std::stack的内容,因此不需要直接支持在代码中执行此操作。

示例:

std::stack

由于在此示例中#include <iostream> #include <stack> namespace cppx { using std::stack; namespace hack { template< class Item > auto container_of( stack<Item> const& st ) -> typename stack<Item>::container_type const& { struct Hacked: stack<Item> { using stack<Item>::c; }; return st.*&Hacked::c; } } // namespace hack template< class Item > auto begin( stack<Item> const& st ) { return hack::container_of( st ).begin(); } template< class Item > auto end( stack<Item> const& st ) { return hack::container_of( st ).end(); } } // namespace cppx auto main() -> int { using namespace std; stack<int> st; for( int const x : {3, 1, 4, 1, 5, 9, 2, 6, 5, 4} ) { st.push( x ); } using cppx::begin; using cppx::end; for( auto it = begin( st ); it != end( st ); ++it ) { cout << *it << " "; } cout << endl; } begin未放置在命名空间end中,因此基于范围的循环无法编译。

我没有这样做,因为在名称空间std中专门用于标准容器的标准函数的合法性(有效性)是我不想进入的问题。我认为这是不允许的,虽然专注于自己的类型就行了。但我不确定。

答案 2 :(得分:1)

[WebMethod] public static void UnLockRequest(string reqID) { int requestId = 0; if (int.TryParse(reqID, out requestId)) { UserInfo lockUser = BLRequest.GetLockerInformationByRequestId(requestId); UserInfo currentUser = HttpContext.Current.Session["CurrentUser"] as UserInfo; if (lockUser != null && currentUser != null && currentUser.IDSID.ToUpper().Equals(lockUser.ID.ToUpper())) { BLRequest.UpdateRequestLockStatus(requestId, 0); } } } 只是一个容器适配器。它接受一种类型的容器(默认情况下为std::stack)作为模板参数,并且可以从此容器的实例构造std::deque的实例,但否则不会公开底层的私有容器和堆栈本身没有迭代设施。