如何将地图转换为集合
how to convert map into set
我在尝试将映射转换为集合时遇到了一些问题我得到了一个"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::对<_Ty1,_Ty2>std::设置<_Kty>::insert(Artiste*&&):不可能将参数1转换为常量std::pair<_Ty1,_Ty2>en‘Artiste*&;'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的回答所示。
相关文章:
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将 Qvector<uint8_t> 转换为 QString
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 在 c++ 中将集合转换为向量和向量转换为字符串时出现运行时异常
- 如何使用for_each,transform,Iterator和lambda的某种组合将STD ::集合的字符串转换为小
- 在集合中转换为小写 C++ 错误 C2664
- 使用shared_ptr<字符串>转换为一个无序集合<字符串>
- 将集合转换为向量的向量
- 具有扩展接口的派生类的集合.如何在没有动态强制转换的情况下访问派生接口
- 将shared_ptr集合转换为weak_ptr集合
- 迭代 Java 集合和对元素进行一些转换的有效方法
- 位到十进制转换的集合
- 如何将地图转换为集合
- 将无理分数转换为四个适当/不适当分数的集合
- 将现有的QPushButtons集合转换为单个数组
- 将文本文件转换为 std::string 数组/集合的最佳方法是什么 C++.