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
我认为这与const
有关。在bool operator <
,但我无法摆脱它,因为创建该集合是必要的。
最佳答案
Angelika Langer 曾经写过一篇关于此的文章:Are Set Iterators Mutable or Immutable? .
您可以通过将 set
排序无关紧要的 Node
成员定义为 mutable
来解决此问题:
mutable bool left, right;
(参见building version in ideone。)
就我个人而言,我会考虑使用map
将不可变部分映射到可变部分的设计。
关于c++ - 错误: assignment of member in read-only object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35315372/