【问题标题】:Declaration of iterator: "does not contain a type"迭代器声明:“不包含类型”
【发布时间】:2012-11-15 18:53:32
【问题描述】:

我很难理解为什么会出现此错误。我指的是 Josuttis 的 STL 书和其他资源,似乎我在下面声明我的迭代器的方式应该有效:

#ifndef LRU_H
#define LRU_H

#include <queue>
#include <iterator>


class LRU
{
public:

   LRU();                           // default constructor
   LRU(int);                        // constructor with argument
   ~LRU();                          // destructor 

   // Methods
   //
   void enqueue(int);               // add datum to the queue
   void dequeue();                  // remove datum from the queue
   void replace();                  // replacement algorithm
   void displayQueue() const;       // display contents of queue

private:

   // Member Data
   //
   const int MAX_SIZE;
   int m_currentCount;

   std::queue<int> m_buffer;
   std::queue<int>::const_iterator iter;

};

#endif

但是我声明我的 const_iterator 的那一行会产生以下编译器错误:

In file included from main.cpp:10:
lru.h:41: error: 'const_iterator' in class 'std::queue<int, std::deque<int, std::allocator<int> > >' does not name a type
In file included from lru.cpp:10:
lru.h:41: error: 'const_iterator' in class 'std::queue<int, std::deque<int, std::allocator<int> > >' does not name a type
lru.cpp: In constructor 'LRU::LRU()':
lru.cpp:17: error: class 'LRU' does not have any field named 'm_pos'
lru.cpp: In constructor 'LRU::LRU(int)':
lru.cpp:23: error: class 'LRU' does not have any field named 'm_pos'

Compilation exited abnormally with code 1 at Thu Nov 15 10:47:31

在导致错误的类中声明迭代器有什么特别之处吗?

【问题讨论】:

    标签: c++ stl iterator queue


    【解决方案1】:

    容器适配器std::queue 没有可公开访问的迭代器。由于std::queue&lt;int&gt; 隐藏在LRU 实现中,您可以考虑使用std::deque&lt;int&gt; 代替。 std::dequestd::queue 在后台使用的默认容器,因此使用它不会导致性能损失。我认为使用它是安全的,只要您不在LRU 界面中公开非队列操作即可。

    【讨论】:

    • 我明白了。我可能早该知道的。鉴于队列数据结构的性质,我想这是有道理的。是否有队列的内部迭代器只允许读取访问?我只想要一个显示队列内容的方法。
    • 不,您无权访问内部。但你可以使用std::deque,并确保不要公开任何非队列访问。
    猜你喜欢
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多