【发布时间】:2011-08-12 06:22:57
【问题描述】:
希望从下面的代码中可以清楚地看出,我想要一组对象 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 > > >' as '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是什么? -
-
不明白算法解决了什么问题。
-
好吧,假设对象是人,键入唯一的姓氏。但我也想跟踪每个不同的名字(如果不止一个),而不需要重复存储姓氏
标签: c++ map iterator set mutable