【发布时间】:2019-10-24 16:34:53
【问题描述】:
我正在尝试实现一个简单的双向地图数据结构。我找到了this 有用的链接,我决定以接受的答案中所述的第二种方式实现它。我的代码:
BiMap.h
template <typename X, typename Y>
class Comparator
{
public:
bool operator() (const std::pair<X, Y*>& e1, const std::pair<X, Y*>& e2) const;
};
template <typename T1, typename T2>
class BiMap
{
public:
void insert(const T1& a, const T2& b);
private:
std::set<std::pair<T1, T2*>, Comparator<T1, T2*>> map1_;
std::set<std::pair<T2, T1*>, Comparator<T2, T1*>> map2_;
};
BiMap.cpp
template <typename X, typename Y>
bool Comparator<X, Y>::operator() (const std::pair<X, Y*>& e1, const std::pair<X, Y*>& e2) const
{
return e1.first < e2.first;
}
template <typename T1, typename T2>
void BiMap<T1, T2>::insert(const T1& t1, const T2& t2)
{
auto itr1 = map1_.emplace(t1, nullptr).first;
auto itr2 = map2_.emplace(t2, nullptr).first;
itr1->second = &(itr2->first); // ERROR
itr2->second = &(itr1->first); // ERROR
}
main.cpp
int main()
{
BiMap<int, string> M;
M.insert(1, "one");
}
在编译时,我收到以下错误:
c:\users\lucieon\source\repos\algorithms\trie\trie\suffixtree.inl(17): error C2440: '=': cannot convert from 'const _Ty1 *' to 'const _Ty2'
1> with
1> [
1> _Ty1=std::string
1> ]
1> and
1> [
1> _Ty2=std::string *
1> ]
1>c:\users\lucieon\source\repos\algorithms\trie\trie\suffixtree.inl(17): note: Conversion loses qualifiers
1>c:\users\lucieon\source\repos\algorithms\trie\trie\suffixtree.inl(12): note: while compiling class template member function 'void trie::BiMap<int,std::string>::insert(const T1 &,const T2 &)'
1> with
1> [
1> T1=int,
1> T2=std::string
1> ]
1>c:\users\lucieon\source\repos\algorithms\trie\trie\trie.cpp(140): note: see reference to function template instantiation 'void trie::BiMap<int,std::string>::insert(const T1 &,const T2 &)' being compiled
1> with
1> [
1> T1=int,
1> T2=std::string
1> ]
1>c:\users\lucieon\source\repos\algorithms\trie\trie\trie.cpp(139): note: see reference to class template instantiation 'trie::BiMap<int,std::string>' being compiled
1>c:\users\lucieon\source\repos\algorithms\trie\trie\suffixtree.inl(18): error C2440: '=': cannot convert from 'const _Ty1 *' to 'const _Ty2'
1> with
1> [
1> _Ty1=int
1> ]
1> and
1> [
1> _Ty2=int *
1> ]
1>c:\users\lucieon\source\repos\algorithms\trie\trie\suffixtree.inl(18): note: Conversion loses qualifiers
我知道 itr1->first 和 itr2->first 分别是 map1_ 和 map2_ 的 const 键的一部分,这可能就是我收到此错误的原因,但这是我可以做到这一点的唯一方法数据结构工作。有什么简单的解决方法吗?
【问题讨论】:
-
这是什么std::set<:pair t2>, Comparator
> map1_;? -
你不能改变
std::set的元素,也许使用std::map存储的不是指针而是迭代器更好? -
@VladfromMoscow 基本上 Comparator 是比较函数,它只在 T1 上排序,假设我想在 int 和 string 之间做一个双向映射,这对将是
std::pair<int, string*>。 -
@lucieon 你还没有理解我的问题。在集合和比较器之间的这条线中逗号的含义是什么?
-
@VladfromMoscow 不是您将自定义比较器函数传递给集合的方式吗?
标签: c++