我在尝试将我的地图转换为一组时遇到了一些问题,我得到了一个带有此成员数据的“Chanson”对象:
std::map<std::string,Artiste*> m_interpretes;
Run Code Online (Sandbox Code Playgroud)
这是我如何将我的添加*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());
}
Run Code Online (Sandbox Code Playgroud)
由于此功能,我收到此错误:
错误 C2664:'std::pair<_Ty1,_Ty2> std::set<_Kty>::insert(Artiste *&&) : 不可能 de convertir le paramètre 1 de const std::pair<_Ty1,_Ty2> en 'Artiste * &&' c:\program files (x86)\microsoft visual studio 11.0\vc\include\set 179 1
知道如何修复它吗?
map 是一种关联数据结构,而 set 只包含无序的项目集合,因此添加一对 (key, value) 对后者无效,仅对前者成立。
要从 a 制作 aset键map,你可以这样做
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;
Run Code Online (Sandbox Code Playgroud)
std::set您尝试使用的构造函数将尝试从您传递给它的范围内的所有内容构造一个元素:
return set<Artiste*> (m_interpretes.begin(), m_interpretes.end());
Run Code Online (Sandbox Code Playgroud)
但该范围的元素类型是
std::pair<const std::string, Artiste*>
Run Code Online (Sandbox Code Playgroud)
这绝对不能转换为Artiste*,这就是为什么您会收到有关无法转换的错误。不过,您可以手动执行此操作:
std::set<Artiste*> s;
for (const auto& pair : m_interpretes) {
s.insert(pair.second);
}
Run Code Online (Sandbox Code Playgroud)