- 论坛徽章:
- 0
|
#include <set>
struct setItem
{
setItem()
{
a = b = 0;
}
int a;
int b;
};
struct insertRule: public binary_function<setItem, setItem, bool>
{
bool operator ()(const setItem& pre, const setItem& aft)
{
if(pre.a == aft.a)
return pre.b < aft.b;
else
return pre.a < aft.a;
}
};
int main
{
std::set<setItem, insertRule> mySet;
//插入
for(int i = 0; i < 20; i++)
{
setItem tmp;
tmp.a = i;
tmp.b = i+1;
mySet.insert(tmp);
}
for(std::set<setItem, insertRule>::iterator it = mySet.begin(); it != mySet.end(); it++)
{
/* 有问题的代码
it->a += 20+1;
it->b += it->a + 20 + 1;
*/
//改成这样就没有问题
setItem* p = const_cast<setItem*>(&(*it));
p->a += 20+1;
p->b += p->a + 20 + 1;
}
return 0;
}
请问高人有什么方法不做从const到非const的强制转换直接操作迭代器?? |
|