c++ - 这个模板代码有什么问题?

标签 c++ templates iterator

#include <iostream>
#include <map>
#include <vector>


template<typename T>
class foo {
    public:
        foo(T val) : m_Value(val) { };
        T get_value() const { return m_Value; };
        void set_value(const T& t) { m_Value=t; };
        bool operator<(const foo<T>& x) { return x.get_value() < m_Value; };
        bool operator==(const foo<T>& x) { return x.get_value() == m_Value; };
    private:
        T m_Value;
};

template<typename T>
class bar {
    public:
        bar() { };
        void print_first() const {
            typename std::map<foo<T>,std::vector<foo<T> > >::iterator it;
            it = m_Map.begin(); //ERROR!
            std::cout << it->first.get_value() << std::endl;
        };
    private:
        std::map<foo<T>,std::vector<foo<T> > > m_Map;
};

int main() {
    bar<int> b;
    b.print_first();
    return 0;
};

我正在尝试编写一个容器,但是成员函数需要使用迭代器,但是当我尝试实际使用迭代器时,出现错误:

testcase.cpp: In member function `void bar<T>::print_first() const [with T =
   int]':
testcase.cpp:33:   instantiated from here
testcase.cpp:24: error: no match for 'operator=' in 'it = std::map<_Key, _Tp,
   _Compare, _Alloc>::begin() const [with _Key = foo<int>, _Tp =
   std::vector<foo<int>, std::allocator<foo<int> > >, _Compare =
   std::less<foo<int> >, _Alloc = std::allocator<std::pair<const foo<int>,
   std::vector<foo<int>, std::allocator<foo<int> > > > >]()'
/usr/include/c++/3.3.3/bits/stl_tree.h:184: error: candidates are:
   std::_Rb_tree_iterator<std::pair<const foo<int>, std::vector<foo<int>,
   std::allocator<foo<int> > > >, std::pair<const foo<int>,
   std::vector<foo<int>, std::allocator<foo<int> > > >&, std::pair<const
   foo<int>, std::vector<foo<int>, std::allocator<foo<int> > > >*>&
   std::_Rb_tree_iterator<std::pair<const foo<int>, std::vector<foo<int>,
   std::allocator<foo<int> > > >, std::pair<const foo<int>,
   std::vector<foo<int>, std::allocator<foo<int> > > >&, std::pair<const
   foo<int>, std::vector<foo<int>, std::allocator<foo<int> > >
   >*>::operator=(const std::_Rb_tree_iterator<std::pair<const foo<int>,
   std::vector<foo<int>, std::allocator<foo<int> > > >, std::pair<const
   foo<int>, std::vector<foo<int>, std::allocator<foo<int> > > >&,
   std::pair<const foo<int>, std::vector<foo<int>, std::allocator<foo<int> > >
   >*>&)

我做错了什么? 提前致谢。

最佳答案

print_first 是一个const 方法。因此成员m_Map也是const,它的begin方法不返回一个普通的iterator,而是一个常量迭代器。改变

typename std::map<foo<T>,std::vector<foo<T> > >::iterator it;

typename std::map<foo<T>,std::vector<foo<T> > >::const_iterator it;

你应该可以开始了。

关于c++ - 这个模板代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6132235/

相关文章:

c++ - C++ 中的 Visual Studio 调试错误

c++ - 内存分配的专用函数导致内存泄漏?

c++ - 我无法从中得到输出

c++模板特征——编译时不包含头文件

c++ - 在结构和模板中试验 union 和位域

c++ - 如何在编译时重复连接字符串?

c++ - 四叉树遍历

c++ - QT : Passing QString to QThread

c++ - 在迭代期间哪个更快的并发队列 <> 与互斥队列 <>

Rust:如何过滤掉 "None"排放?