c++ - 自定义对象的 STL 集,每个包含一个 STL 集

标签 c++ map iterator set mutable

希望从下面的代码中可以清楚地看出,我想要一组对象 objectSet,每个对象都包含 str1 和 str2。该集合以 str1 为键,不会添加 objectSet 中已有 str1 的任何新对象,但如果这个新对象具有不同的 str2,我想跟踪我在 str2Set 中看到它的事实

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <set>
#include <map>

using namespace std;

class Object {
public:
  string _str1;
  string _str2;
  set<string> _str2Set;

  bool operator<(const Object& b) const {
    return _str1 < b._str1;
  }
};

int main(int argc, char *argv[]) {
  set<Object> objectSet;

  Object o;
  o._str1 = "str1";
  o._str2 = "str2";

  pair< set<Object>::iterator, bool> o_ret = objectSet.insert(o);
  if (o_ret.second == false) { // key exists
    int temp = (*o_ret.first)._str2Set.size(); // this is apparently fine
    (*o_ret.first)._str2Set.insert(o._str2); // this results in the error
  }

  return 0;
}

这是编译错误:

set_test.cpp: 在函数‘int main(int, char**)’中: set_test.cpp:31: 错误:传递 'const std::set, std::allocator >, std::less, std::allocator >>, std::allocator, std::allocator >> >' 作为 'this 'std::pair, _Compare, typename _Alloc::rebind<_Key>::other>::const_iterator, bool> 的参数 std::set<_Key, _Compare, _Alloc>::insert(const _Key&) [with _Key = std::basic_string, std::allocator >, _Compare = std::less, std::allocator >>, _Alloc = std::allocator, std::allocator >>]' 丢弃限定符

我知道这与 const 有关,但我仍然无法确切地弄清楚问题是什么或如何解决它。仅仅摆脱 const 并没有帮助。

作为替代方案,我尝试将我的对象存储在

map<string,Object> objectSet;

而且,奇怪的是,以下工作正常:

  pair< map<string,Object>::iterator, bool> o_ret = objectSet.insert(pair<string,Object>(o._str1,o));
  if (o_ret.second == false) { // key exists
    o_ret.first->second._str2Set.insert(o._str2);
  }

当然,这意味着我必须存储 str1 两次,我认为这是浪费。 感谢您的输入。

最佳答案

您的设计有缺陷。您正在使用 Object 作为集合的键,但随后您正试图修改集合的键。当然,您只是修改了不影响其用作键的 Object 部分,但编译器并不知道这一点。你需要修改你的设计,你的第二个版本对我来说很好,我不担心将字符串存储两次(通常,我不知道你的具体情况)。或者,您可以拆分对象,以便将关键部分和值(value)部分分开。最后,您可以将 _str2set 声明为可变的。

关于c++ - 自定义对象的 STL 集,每个包含一个 STL 集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7036334/

相关文章:

c++ - std::map::iterator 是否返回值的拷贝或值本身?

c++ - 函数 pow() int C++

c++ - 在 C++ 中读取文本文件时如何跳过特定列?

grails - 在Grails中为 map 值建模的最佳方法?

c++ - STL::map 插入一个带约束的值

arrays - 如何在 Rust 0.8 中将 Zip 转换为数组?

c++ - OpenCV中不同变形方法之间的区别

c++ - 如何将 C++ 变量存储在寄存器中

c++ - 为什么C++ STL map容器的复杂度是O(log(n))?

c++ - 迭代器和模板