为什么一个简单的bimap(std::string <-> int)不起作用?
Why a simple bimap ( std::string <-> int) does not work?
一个
令人费解的模板和类型转换问题如下所示C++...为了让我的生活更轻松,我定义了一个模板类来使用类 BiMap 对一对一关系进行建模:
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <string>
template<class T1, class T2>
class BiMap {
public:
T2& operator[] (T1& t1) {
return d1[t1];
}
T1& operator[] (T2& t2) {
return d2[t2];
}
private:
std::map<T1, T2> d1;
std::map<T2, T1> d2;
};
int main(int argc, char *argv[])
{
BiMap<std::string, int> m;
m["1"] = 2;
m[2] = 3;
printf("%d", m["1"]);
printf("%d", m[2]);
return 0;
}
但是我得到这个编译错误:
testPedigree.cpp:45: error: no match for ‘operator[]’ in ‘m["1"]’
testPedigree.cpp:16: note: candidates are: T2& BiMap<T1, T2>::operator[](T1&) [with T1 = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, T2 = int]
testPedigree.cpp:19: note: T1& BiMap<T1, T2>::operator[](T2&) [with T1 = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, T2 = int]
我期待C++会自动将 const char* 转换为 std::string,因为我在这篇文章中提出了这个问题:为什么我可以在 std::map<std::string,>
您的代码尝试将非const
引用绑定到临时引用(即从const char[]
隐式创建的std::string
)。只有const
引用可以绑定到临时引用。
尝试:
T2& operator[] (const T1& t1) {
return d1[t1];
}
T1& operator[] (const T2& t2) {
return d2[t2];
}
示例中还有其他一些琐碎的错误。这是一个经过更正、测试的程序:
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <string>
template<class T1, class T2>
class BiMap {
public:
T2& operator[] (const T1& t1) {
return d1[t1];
}
T1& operator[] (const T2& t2) {
return d2[t2];
}
private:
std::map<T1, T2> d1;
std::map<T2, T1> d2;
};
int main(int argc, char *argv[])
{
BiMap<std::string, int> m;
m["1"] = 2;
m[2] = "3";
printf("%d", m["1"]);
printf("%sn", m[2].c_str());
return 0;
}
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 呼叫运营商<<临时
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 调用'begin(int [n])'没有匹配函数
- 错误:调用"std::vector<:vector<int>>::p ush_back(std::vector<std::__cxx11::basic_string<
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- 运营商&lt;&lt;无法访问班级的私人int
- std::pair的默认构造函数<>将基本类型(int等)设置为零
- 如何显示/打印字符串对象?cout & lt; & lt;Int工作,count <<字符串