如何将地图转换为集合

how to convert map into set

本文关键字:集合 转换 地图      更新时间:2023-10-16

我在尝试将映射转换为集合时遇到了一些问题我得到了一个"Chanson"对象,其中包含以下成员数据:

std::map<std::string,Artiste*> m_interpretes;

以下是我如何将我的*Artiste添加到我的地图:

void Chanson::addArtiste(Artiste* a) throw (ExceptionArtiste, ExceptionLangueIncompatible)
{
    if(a!=NULL)
    {
        if(a->getLangue() == this->getLangue())
        {
            m_interpretes.insert(pair<string, Artiste*>(a->getNom(), a));
            //m_interpretes[a->getNom()] = a;
        }
        else
        {
            throw ExceptionLangueIncompatible(a,this);
        }
    }
}


set<Artiste*> Chanson::getArtistes() const
{
    //set<Artiste*> machin;
    return set<Artiste*> (m_interpretes.begin(), m_interpretes.end());
}

我得到这个错误是由于这个功能:

错误C2664:"std::对&lt_Ty1,_Ty2>std::设置&lt_Kty>::insert(Artiste*&&):不可能将参数1转换为常量std::pair&lt_Ty1,_Ty2>en‘Artiste*&amp;'c: \program files(x86)\microsoft visual studio 11.0\vc\include\set 179 1

知道怎么修吗?

映射是一个关联数据结构,而集合只包含无序的项集合,因此添加一对(键、值)对后者无效,仅对前者有效。

要从map生成密钥的set,可以执行

std::set<Artiste*> tempSet;
std::transform(m_interpretes.cbegin(), m_interpretes.cend(),
               std::inserter(tempSet, tempSet.begin()),
               [](const std::pair<std::string, Artiste*>& key_value)
               { return key_value.second; });
return tempSet;

您尝试使用的std::set构造函数将尝试从您传递给它的所有范围中构造一个元素:

return set<Artiste*> (m_interpretes.begin(), m_interpretes.end());

但该范围的元素类型是

std::pair<const std::string, Artiste*>

它绝对不能转换为Artiste*,这就是为什么你会得到无法转换的错误。不过,你可以手动完成:

std::set<Artiste*> s;
for (const auto& pair : m_interpretes) {
    s.insert(pair.second);
}

问题就在这里:

return set<Artiste*> (m_interpretes.begin(), m_interpretes.end());

如果你看一下从map::begin()和map::end()函数中得到的类型,你会发现你得到了std::pair<string, Artiste*>的迭代器。

问题是,set::insert()函数要求它所给定的迭代器的类型为Artiste*

最简单的解决方法是创建一个带有for循环的集合,如Barry的回答所示。