我知道当我们将值插入 STL 映射时,会制作并存储一个拷贝。 我的代码本质上是在 map 上进行查找并获取迭代器。
然后我打算使用迭代器来更改映射中的值。 结果不是我所期望的,即:当从程序的另一部分访问时,该值没有改变。我怀疑是因为我正在应用的更改是针对 值(value)。 相关代码如下。
ObjectMappingType::iterator it = objectMapping_.find(symbol);
if (it == objectMapping_.end()) {
throw std::invalid_argument("Unknown symbol: " + symbol);
}
get<3>(it->second) = value;
注意:我实际上是在尝试更改存储为映射的“值”部分的 boost::tuple 中的值。
最佳答案
嗯……这两种方法对我来说似乎都很有效。这是我使用的整个示例:
#include <iostream>
#include <map>
#include <string>
#include <boost/tuple/tuple.hpp>
typedef boost::tuple<int, std::string> value_type;
typedef std::map<int, value_type> map_type;
std::ostream&
operator<<(std::ostream& os, value_type const& v) {
os << " number " << boost::get<0>(v)
<< " string " << boost::get<1>(v);
return os;
}
int
main() {
map_type m;
m[0] = value_type(0, "zero");
m[1] = value_type(0, "one");
m[2] = value_type(0, "two");
std::cout
<< "m[0] " << m[0] << "\n"
<< "m[1] " << m[1] << "\n"
<< "m[2] " << m[2] << "\n"
<< std::endl;
boost::get<0>(m[1]) = 1;
map_type::iterator iter = m.find(2);
boost::get<0>(iter->second) = 2;
std::cout
<< "m[0] " << m[0] << "\n"
<< "m[1] " << m[1] << "\n"
<< "m[2] " << m[2] << "\n"
<< std::endl;
return 0;
}
输出正是我所期望的。
lorien$ g++ -I/opt/include -gdwarf-2 foo.cpp
lorien$ ./a.out
m[0] number 0 string zero
m[1] number 0 string one
m[2] number 0 string two
m[0] number 0 string zero
m[1] number 1 string one
m[2] number 2 string two
lorien$
关于c++ - 就地更改 STL map 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1977486/