为什么我不能在std :: set中的元素上调用非const成员函数? [英] Why can't I call a non-const member function on an element in an std::set?

查看:292
本文介绍了为什么我不能在std :: set中的元素上调用非const成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个代码:

  set< Item> temp_items; 
set< Item> :: iterator it;
temp_items = user-> second.get_items();
for(it = temp_items.begin(); it!= temp_items.end(); it ++)
{
if(counter ==(choice - 1))
{
it-> get_count();
}
}

我试图调用的项目功能是:

  int Item :: get_count(){return _count; } 

我这里没有任何会阻止我访问item对象的const类型,然后,我收到下一条消息:


该对象具有与成员函数不兼容的类型限定符



对象类型是const


我该如何解决?

解决方案

简而言之:你只能在set迭代器上调用const函数。



说明:



该组在内部按 Item 排序。因此,当您访问引用(通过迭代器)时,您不允许执行某些操作来更改 Item 的值(这在以前的c ++版本中实际上很容易实现)。



当您意外更改值时,会发生什么情况,这不会相应地改变内部排序,即使对象在理论上存在,查找也会失败。 / p>

想象一下这个数字你有一套

  1 2 3 4 5 6 7 8 9 

现在将值9更改为0(按引用)

  1 2 3 4 5 6 7 8 0 

现在当你想要一个0并且容器有一个智能查找时,它将使用二进制搜索并假设0在最左边。这将导致0未找到。



注意:这只是一个简化的例子。没有明确说明如何实现一套)



这就是为什么对键的引用是 const 引用以及为什么你只能在那些上调用const函数(同样适用于键上的键)地图)。


I hve the next code:

set<Item> temp_items;
set < Item >::iterator it;
temp_items = user->second.get_items();
for (it = temp_items.begin(); it != temp_items.end(); it++)
{
    if (counter == (choice - 1))
    {
        it->get_count();
    }
}

The item function i trying to call is:

int Item::get_count() { return _count; }

I don't have in here any const type that should prevent me from accessing the item object, and still, I get the next message:

the object has type qualifiers that are not compatible with the member function

object type is const

How can I fix it?

解决方案

In short: you can only call const functions on set iterators.

Explanation:

The set is internally sorted by the Item. So when you access a reference (via iterator) you are not allowed to do something to change the value of the Item (this was actually easily possible in earlier c++ versions).

What happens when you accidentally change the value this would not change the internal "ordering" accordingly and the lookup can fail even while the object is "there" in theory.

Imagine this with numbers you have a set

1 2 3 4 5 6 7 8 9

Now you change the value of 9 to 0 (by reference)

1 2 3 4 5 6 7 8 0

Now when you would look for a 0 and the container has a smart lookup it would use a binary search and would assume 0 is on the far left. This would result in 0 not being found.

(Note: this is just a simplified example. Not a definite explanation on how a set is implemented)

That is why the reference to the key is a const reference and why you only can call const functions on those (same applies for keys on a map).

这篇关于为什么我不能在std :: set中的元素上调用非const成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆