在C++中设置映射*的键和值

Set key and value of a map* in C++

本文关键字:键和值 映射 设置 C++      更新时间:2023-10-16

我在下面http://www.cplusplus.com/reference/map/map/map/.

我正在尝试构建一个反转索引结构,这是一个以64位整数为键的映射,每个键都将包含一个子映射的指针。子映射将包含int-int对。所以我写了一些样本:

map<unsigned long long int, map<int, int>*> invertID;
int main(int argc, char *argv[]){
    map<int,int>* m = new map<int,int>();
    m[10] = 1;
    invertID[1] = m;
    return 0;
}

但是,对于像这样的非指针类型的地图来说,通常情况下,问题是

std::map<char,int> first;

如中所述http://www.cplusplus.com/reference/map/map/map/,我看到我们可以做

first['a']= 10;

但是如果我们有一个map的指针类型,我们怎么能做到呢我上面的代码将生成一个错误报告

error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)

您可以取消引用指针:

 (*m)[10] = 1;

m->operator[](10) = 1;

另一方面,你真的需要所有这些指针吗?您的程序会因为使用此表单而受到很大影响吗?

map<unsigned long long int, map<int, int>> invertID;
int main()
{
    map<int,int> m;
    invertID[1][10] = 1;
}

Map是一个红黑树,其中包含操作,因此您可以使用它来获得最佳搜索和插入性能。。等等。您在inversidID中使用的是贴图而不是多贴图。因此,在大多数情况下,当您获取某个密钥时,我会假设您正在寻找一对元素。除非你出于我现在没有想到的任何原因需要第二张地图,否则我会选择这个:

std::map < unsigned long long int, std::pair < int , int >  > invertID;
int main(){
    std::pair<int,int>  m;
    m = std::make_pair(1,2);
    invertID[1] = m;
    return 0;
}

玩得开心。