簡體   English   中英

如何訪問指向地圖的元素?

[英]How can I access the elements of a pointer-to-map?

我已通過指向函數的指針傳遞了地圖,但現在由於代碼無法編譯,因此無法更改地圖的內容。 我不確定是否甚至允許我將地圖作為指針傳遞。 例如:

#include <iostream>
#include <stdlib.h>
#include <map>
#include <string>
using namespace std;

void faa(map<int,string> *baa){
   *baa[1] = "somethingnew";
}

int main(){
    map<int,string> bar;
    bar[1] = "one";
    bar[2] = "two";
    bar[3] = "three";

    int ii;
    for(ii=1;ii<4;ii++){
        cout<<"bar["<<ii<<"]="<<bar[ii]<<endl;
    }

    faa(&bar);
    cout<<"after"<<endl;
    for(ii=1;ii<4;ii++){
        cout<<"bar["<<ii<<"]="<<bar[ii]<<endl;
    }
}

當我編譯這個我得到錯誤:

error: no match for ‘operator*’ (operand type is ‘std::map >’)
     *baa[1] = "somethingnew";

有可能像faa這樣的功能嗎? 語法是什么?

由於運算符優先級規則, *baa[1]被解析為*(baa[1])而不是(*baa)[1] 您可以在括號中加上使其生效。 但是,最好使用引用代替:

void faa(map<int,string> &baa){
   baa[1] = "somethingnew";
}

然后,您只需調用該函數,而無需獲取地圖的地址:

faa(bar);

您可以改用(*baa)[1]

默認優先級與您寫*(baa[1])

解釋錯誤消息:如果baa是指針,則可以使用[]運算符訪問指針指向的第n個元素,因此baa[1]的類型為std::map ,並且沒有*運算符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM