C++ can use (reference) to get the value address in the STL container but cannot change its value.
習慣沉默
習慣沉默 2017-05-16 13:28:05
0
3
653
class TempTest{ public: int _uid; }; bool getTestData(std::map& vec,short id,TempTest &data){ auto it = vec.find(id); if (it != vec.end()) { data = it->second; return true; } return false; } int main(){ std::map testMap; // create data TempTest testTemp; testTemp._uid = 1054; testMap[1] = testTemp; TempTest tempData1; // 获取出其引用 getTestData(testMap, 1, tempData1); // 改变其值 tempData1._uid = 9918; // 这样是可以修改成功 可是 感觉 太沉余代码了 想封装成函数... //auto it = testMap.find(1); //if (it != testMap.end()) { // it->second._uid = 9918; //} for (auto &itor:testMap) { std::cout<

Thank you for your help.

習慣沉默
習慣沉默

reply all (3)
仅有的幸福

You have a wrong understanding of references
getTestData(testMap, 1, tempData1);
This statement does not make tempData1 become a reference to testMap[1]. This function just makes all operations on data in the function reflect the same to tempDada1, so data becomes a reference to tempData1. And your tempdata1 does not reference any elements in testMap at all, so changing tempdata1 will have no effect.

    某草草

    In the getTestData function, your assignment statement data=it-

    The solution is to override the copy constructor so that it returns the original object. There is also a way to use pointers.

      Ty80

      Change getTestData to setTestData and use data to assign value to it->second

        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!