这个模板代码有什么问题

What is wrong with this template code?

本文关键字:什么 问题 代码      更新时间:2023-10-16
#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,而是返回const_iterator。更改

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

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

你应该很乐意去。