如何重载和打印 map<map<list<int>*, vector<int>, myFunctorClass>*, int, myFunctorClass> M1

how to overload and print map<map<list<int>*, vector<int>, myFunctorClass>*, int, myFunctorClass> M1

提问人:Jack Yanchen Li 提问时间:4/19/2023 最后编辑:Jack Yanchen Li 更新时间:4/21/2023 访问量:36

问:

我尝试打印map<map<list,vector,myFunctorClass>,int,myFunctorClass> M1,如下所示:

    map<map<list<int>*, vector<int>, myFunctorClass>*, int, myFunctorClass> M1{
     {
        new map<list<int>*, vector<int>, myFunctorClass>{
            {new list<int>({91, 92, 93, 94}), vector<int>({5, 6, 7, 8})},
            {new list<int>({11, 12, 13, 14}), vector<int>({5, 6, 7, 8})},
            {new list<int>({12, 22, 32, 42}), vector<int>({5, 6, 7, 8})}
        }, 1
    },
    {
        new map<list<int>*, vector<int>, myFunctorClass>{
            {new list<int>({11, 21, 31, 41}), vector<int>({51, 61, 71, 81})}
        }, 100
    },
    {
        new map<list<int>*, vector<int>, myFunctorClass>{
            {new list<int>({12, 22, 32, 42}), vector<int>({52, 62, 72, 82})}
        }, 16
    }
};
cout << M1 << endl;

我使用模板使运算符重载<<

template<class T> ostream& operator<<(ostream& str, const map<T*, int, myFunctorClass>& M);
template<class T>ostream& operator<<(ostream& str, const list<T*>& L);
template<class T>ostream& operator<<(ostream& str, const vector<T>& v);
template <class T1, class T2> ostream& operator<<(ostream& str, const map<T1*, T2, myFunctorClass>& m);

template<class T>ostream& operator<<(ostream& str, const list<T*>& L) {
str << " < ";
for (auto& i : L) {
    str << *i << " ";
}
str << " > ";
return str;
}
template<class T>ostream& operator<<(ostream& str, const vector<T>& v) {
str << " [ ";
for (auto& i : v) {
    str << i << " ";
}
str << " ] ";
return str;
}
template <class T1, class T2> ostream& operator<<(ostream& str, const map<T1*, T2, myFunctorClass>& m) {
str << "{ ";
for (auto i : m) {
    str << *i.first << " " << i.second;
}
str << "}";
return str;
}
template<class T>ostream& operator<<(ostream& str, const map<T*, int, myFunctorClass>& M) {
str << "{\n";
for (auto& i : M) {

    str << " { " << i.first;
    str << " " << i.second;
    str << " }\n";
}

str << " \n}";
return str;
}

但是,我只能得到这样的结果

{
   { 000001EE7768F950 1 }

}

它应该打印如下内容(数字不匹配):

{
{ < 1 2 3 > [ 5 6 7 8 ] < 4 5 3 > [ 15 6 7 8 ] < 11 2 3 > [ 5 26 7 8 ]  2 }
{ < 1 2 3 > [ 5 116 7 8 ] < 4 5 3 > [ 15 6 7 8 ] < 11 2 3 > [ 5 26 7 8 ]  100 }
{ < 1 2 13 > [ 5 26 17 8 ] < 31 2 3 > [ 5 6 77 8 ] < 45 15 3 > [ 11 6 17 8 ]  50 }
}

我做错了什么,它只打印地址,而只打印整个地图中的一个元素?

C++ 字典 模板 运算符重载 函子

评论

0赞 463035818_is_not_an_ai 4/19/2023
请发布一个最小的可重复示例
0赞 463035818_is_not_an_ai 4/19/2023
为什么你的代码中有这么多指针?

答:

0赞 RandomBits 4/21/2023 #1

最后一个函数被调用,它只执行一次循环,因为顶级映射中有一个元素。它按预期打印指向的指针和整数。我假设您希望它输出值而不是指针。您需要将 替换为 。operator<<MT1Ti.first*i.first

这应该产生如下内容:

{
    { { 0x60000362d1e0  [ 5 6 7 8  ] } 1 }
}

同样,您可能希望输出内部结构的值而不是指针。