[英]error: assignment of member in read-only object
IDEONE: http ://ideone.com/ uSqSq7
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
using namespace std;
struct node
{
int value, position;
bool left, right;
bool operator < (const node& a) const
{
return value < a.value;
}
};
int main()
{
int n;
cin >> n;
vector < node > a(n);
set < node > s;
for (auto &i: a)
{
cin >> i.value;
i.left=i.right=0;
}
a[0].position=1;
s.insert(a[0]);
for (int i=1; i<n; i++)
{
auto it=s.upper_bound(a[i]);
auto it2=it; --it2;
if (it==s.begin())
{
a[i].position=2*it->position;
s.insert(a[i]);
it->left=1;
}
else if (it==s.end())
{
a[i].position=2*(--it)->position+1;
s.insert(a[i]);
it->right=1;
}
else
{
if (it2->right==0)
{
a[i].position=2*it2->position+1;
s.insert(a[i]);
it2->right=1;
}
else
{
a[i].position=2*it->position;
s.insert(a[i]);
it->left=1;
}
}
}
for (auto i: a) cout << i.position << ' ';
}
当我编译这段代码时,我得到
error: assignment of member 'node::right' in read-only object
我认为这与bool operator <
的const
有关,但是我无法摆脱它,因为有必要创建集合。
Angelika Langer曾经写过一篇文章: Set Iterators Mutable or Immutable? 。
您可以通过定义解决这个Node
成员无关紧要的set
排序为mutable
:
mutable bool left, right;
就个人而言,我将考虑使用map
将不可变部分映射为可变部分的设计。
问题:
请记住,std :: set中的键是恒定的。 将密钥插入集合后,您将无法更改它。 因此,当取消引用迭代器时,它必然返回一个常量引用。
const node& n = (*it);
n->left = 1; //It will not allow you to change as n is const &.
解:
正如Ami Tavory回答的那样,您可以将左右声明为可变的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.