使用包含 set 作为值的映射
基本上我有,
typedef map<std::string, set<double> > MAP_STRING_TO_SET;
用新值更新(添加或删除值)集合而不导致集合被复制的最佳方法是什么?
我看到的唯一可行的解决方案是使用 map
——这是我不想做的。
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该集合仅在初始化时被复制。
您可以执行类似的操作。
由于 map::operator[] 返回一个引用,因此
The set is only copied in initialization.
You are allowed to do something like
since map::operator[] returns a reference.
您还可以这样做:
You can also do this:
我认为你可以只使用交换 - 例如。
提供的破坏
my_set
对你来说并不重要。 这会将my_map["123"]
之前的内容替换为my_set
,而且速度很快。索引运算符[]返回对所包含的
集合
的引用 - 因此,您可以像任何其他变量一样操作它。 如果您想添加/删除单个值,您只需使用insert()
或erase()
方法 - 例如。my_map["123"].insert(123)
。当您将一组新的地图分配给地图时,实际上会发生复制 - 例如。
将创建
my_set
的副本。 如果以后不需要使用my_set
的值,可以使用swap()
方法,该方法只会打乱两个集合的指针。 但是,my_set
将具有之前my_map["123"]
的内容。I think you can just use swap - eg.
provided clobbering
my_set
doesn't matter to you. This would swap the previous contents ofmy_map["123"]
withmy_set
, and it's fast.The indexing operator[] returns a reference to the contained
set
- therefore, you can manipulate it just like any other variable. If you want to add/remove individual values, you can just useinsert()
orerase()
methods - eg.my_map["123"].insert(123)
.The copying actually takes place when you assign a new set to the map - eg.
would create a copy of
my_set
. If you don't need to use the value ofmy_set
later, you can use theswap()
method, which will just shuffle pointers of the two sets.my_set
will, however, have the contents of the previousmy_map["123"]
.