使用包含 set 作为值的映射

发布于 2024-07-16 09:06:43 字数 271 浏览 4 评论 0 原文

基本上我有,

typedef  map<std::string, set<double> > MAP_STRING_TO_SET;

用新值更新(添加或删除值)集合而不导致集合被复制的最佳方法是什么?

我看到的唯一可行的解​​决方案是使用 map* > ——这是我不想做的。

谢谢

Basically I have,

typedef  map<std::string, set<double> > MAP_STRING_TO_SET;

What is the best way to update (add or remove value) the set with a new value without causing the set to be copied?

The only viable solution I see is to use map<std::string, set<double>* > -- something I don't want to do.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

紙鸢 2024-07-23 09:06:43

该集合仅在初始化时被复制。
您可以执行类似的操作。

myMap[myString].insert(myDouble);

由于 map::operator[] 返回一个引用,因此

The set is only copied in initialization.
You are allowed to do something like

myMap[myString].insert(myDouble);

since map::operator[] returns a reference.

或十年 2024-07-23 09:06:43

您还可以这样做:

map<std::string, set<double> >::iterator iter = myMap.find(myString);
if(iter != myMap.end())
{
 iter->second.insert(myDouble);
}

You can also do this:

map<std::string, set<double> >::iterator iter = myMap.find(myString);
if(iter != myMap.end())
{
 iter->second.insert(myDouble);
}
明月夜 2024-07-23 09:06:43

我认为你可以只使用交换 - 例如。

my_map["123"].swap(my_set)

提供的破坏 my_set 对你来说并不重要。 这会将 my_map["123"] 之前的内容替换为 my_set,而且速度很快。

索引运算符[]返回对所包含的集合的引用 - 因此,您可以像任何其他变量一样操作它。 如果您想添加/删除单个值,您只需使用 insert()erase() 方法 - 例如。 my_map["123"].insert(123)

当您将一组新的地图分配给地图时,实际上会发生复制 - 例如。

my_map["123"]=my_set

将创建 my_set 的副本。 如果以后不需要使用 my_set 的值,可以使用 swap() 方法,该方法只会打乱两个集合的指针。 但是,my_set 将具有之前 my_map["123"] 的内容。

I think you can just use swap - eg.

my_map["123"].swap(my_set)

provided clobbering my_set doesn't matter to you. This would swap the previous contents of my_map["123"] with my_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 use insert() or erase() methods - eg. my_map["123"].insert(123).

The copying actually takes place when you assign a new set to the map - eg.

my_map["123"]=my_set

would create a copy of my_set. If you don't need to use the value of my_set later, you can use the swap() method, which will just shuffle pointers of the two sets. my_set will, however, have the contents of the previous my_map["123"].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文