Why Can't I store references in a `std::map` in C++?

后端 未结 6 1164
执念已碎
执念已碎 2020-12-02 19:55

I understand that references are not pointers, but an alias to an object. However, I still don\'t understand what exactly this means to me as a programmer, i.e. what are re

6条回答
  •  忘掉有多难
    2020-12-02 20:37

    actually you can use references in a map. i don't recommend this for big projects as it might cause weird compilation errors but:

        map no_prob;
        int refered = 666;
        no_prob.insert(std::pair(0, refered)); // works
        no_prob[5] = 777; //wont compile!!! 
        //builds default for 5 then assings which is a problem
        std::cout << no_prob[0] << std::endl; //still a problem
        std::cout << no_prob.at(0) << std::endl; //works!!
    

    so you can use map but it will be difficult to guaranty it will be used correctly, but i used this for small codes (usually competitive) codes

提交回复
热议问题