【问题标题】:Search Map & Print Vector搜索地图和打印矢量
【发布时间】:2018-12-01 21:53:16
【问题描述】:

我有一个 STL 映射,它将键映射到可交付成果的向量。 我想在地图上搜索某个键并打印出所有可交付成果。我正在尝试遍历向量并在每个项目上调用 print。

typedef std::vector<Deliverables>      MyDeliverables;
typedef std::map<int, MyDeliverables> MyMap;

MyMap map1;

template < class T >

void printVector( const vector <T> &v)
{
    for (auto p = v.begin(); p != v.end(); ++p)
        *p->print();
}


int main()
{   
Deliverables del("Name", 12, 12, 2018);

map1.insert(MyMap::value_type(1, MyDeliverables()));

auto search = map1.find(1);
if (search != map1.end()) {
    std::cout << "Found Student ID: " << search->first << '\n';
    printVector(search->second);
}
else {
    std::cout << "Not found\n";
}
}

错误 C2662“void Deliverables::print(void)”:无法将“this”指针从“const Deliverables”转换为“Deliverables &”
行:*p->print();

如何正确打印可交付成果?

【问题讨论】:

    标签: c++ vector


    【解决方案1】:

    问题在于您没有显示的代码:

    Deliverables::print()
    

    不是const,所以不能使用。将 print 函数声明为 const,然后就可以使用const Deliverables&amp;

    Deliverables::print() const
    

    然后更改循环以避免混淆要取消引用的内容和次数:

    for(const auto& p: v)
        p.print();
    

    【讨论】:

    • 如果使用普通的 for,p->print() 没有额外的取消引用也是必要的,至少在 print() 不返回指针的情况下。
    • @Christophe 确实,额外的* 将被编译器标记为试图取消引用 void 返回。添加了关于为什么更改 for 循环更好的评论。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多