简体   繁体   English

对 C++ 映射的 map.find() 实现错误

[英]Error in implementation of map.find() for map of pairs C++

I have a map like this我有一张这样的地图

map<int,pair<int,int>>diff;

I am using it like this我像这样使用它

int temp;
    for(int i=0;i<n-1;i++)
    {
        for(int j=i+1;j<n;j++)
        {
            temp=v[j]-v[i];
            if(temp>0)
            {
                if(diff.find(temp)!=diff.end())
                {
                    pair<int,int> a=diff.find(temp);
                    if(a.second>j)
                    {
                        a.second=j;
                        a.first=i;
                    }
                }
                else
                {
                    map.insert({temp,{i,j}});
                }
            }
        }
    }    

where n is the size of vector v .其中n是向量v的大小。

The error I am getting is我得到的错误是

error: conversion from ‘std::map<int, std::pair<int, int> >::iterator {aka std::_Rb_tree_iterator<std::pair<const int, std::pair<int, int> > >}’ to non-scalar type ‘std::pair<int, int>’ requested

pair<int,int> a=diff.find(temp);

I looked online and I found that if element exists then map.find() returns to the position of element in the vector so in this it should return the pair to the element right?我在网上查看,我发现如果元素存在,则 map.find() 返回到向量中元素的位置,因此在此它应该将配对返回到元素,对吗?

What am I doing wrong?我究竟做错了什么?

The error message explains exactly what is wrong.错误消息准确地说明了错误所在。 You are trying to initialise a pair<int, int> with an decltype(diff)::iterator .您正在尝试使用decltype(diff)::iterator初始化pair<int, int>

The simple fix is to dereference the result of find , or to use at简单的解决方法是取消引用find的结果,或使用at

pair<int,int> a=diff.at(temp);

Note that this is a copy, not a reference, so the following actions are discarded.请注意,这是一个副本,而不是一个引用,因此以下操作将被丢弃。

A better fix is to use the iterator from the first find更好的解决方法是使用第一次find的迭代器

auto it = diff.find(temp);
if(it!=diff.end())
{
    if(it->second>j)
    {
        it->second=j;
        it->first=i;
    }
}
else
{
    map.insert({temp,{i,j}});
}

Note that map::insert returns a useful value, and it doesn't overwrite existing values.请注意map::insert返回一个有用的值,它不会覆盖现有值。 You can simplify even further:您可以进一步简化:

auto [it, unused] = map.insert({temp,{i,j}});
if (it->second < j)
{
    it->second=j;
    it->first=i;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM