- 论坛徽章:
- 0
|
代码中有这样一个map
map<string, BigClass>
其中BigClass是一个较大的类。
需要修改BigClass时,为了减少时间。使用引用来操作某个关键字对应的BigClass
但是看到iterator的second的注释是second is a copy of the second object
难道返回的是重新构造的一个临时变量吗。这样就不能通过下面的引用来修改了
BigClass& big = iter->second;
做了下面的一个测试,上面的BigClass用string代替了,是可以修改的。到底可不可以这样用呢。- #include <map>
- #include <string>
- using namespace std;
- void fun(map<string, string>& _map)
- {
- _map.clear();
- string ctxKey = "KEY";
- _map[ctxKey] = "AAAAA";
-
- std::map<string, string>::iterator iter = _map.find( ctxKey );
- string &s = iter->second;
- s = "BBBBB";
- }
- int main(int argc, char *argv[])
- {
- map<string, string> _map;
-
- fun(_map);
- printf("%s\n", _map["KEY"].c_str());
-
- return 0;
- }
复制代码 |
|