How to update set of pointers c++?

余生颓废 提交于 2019-12-13 05:37:21

问题


I need a group of TVertex objects to have an access to their sortings by diffrent parameters (id and flow). To find the kth element in O(1) time and to update their properties in o(log2(N)) time.

To do this I use TComparatorF and TComparatorI classes.

They both have a pointer to TVertex and operators > and <

TComparatorF compares flows

TComparatorI compares ids

TVertex() puts a pointer to itself to a comparator. And then puts the comparator to a set of comparators.

But when I update properties of TVertex object, position of relative to it comparator doesn't change.

Is there a way to force my sets to update or a better idea for storing multiple sortings?

Code:

#include<stdio.h>
#include<set>
#include<stdlib.h>
using namespace std;
const int N=300000;

struct TVertex;
struct TComparatorF
{
    TVertex *cmp;
    bool operator >(const TComparatorF &other) const;
    bool operator <(const TComparatorF &other) const;  
};
struct TComparatorI
{
    TVertex *cmp;
    bool operator >(const TComparatorI &other) const;
    bool operator <(const TComparatorI &other) const;  
};
set <TComparatorF> flowset;
set <TComparatorI> idset;
struct TVertex
{
    int flow,id;  
    TVertex();
};
bool TComparatorF::operator >(const TComparatorF &other) const
{
    return !(*cmp).flow>(*(other.cmp)).flow;   
}
bool TComparatorF::operator <(const TComparatorF &other) const
{
    return !(*cmp).flow<(*(other.cmp)).flow;
}
bool TComparatorI::operator >(const TComparatorI &other) const
{
    return !(*cmp).id>(*(other.cmp)).id;   
}
bool TComparatorI::operator <(const TComparatorI &other) const
{
    return !(*cmp).id<(*(other.cmp)).id;
}
TVertex::TVertex()
{
    flow=0;
    TComparatorF comp;
    comp.cmp=this;    
    flowset.insert(comp);
    TComparatorI comp2;
    comp2.cmp=this;
    idset.insert(comp2);
}
TVertex ver[N];

int main()
{
    ver[0].flow=17;
    ver[0].id=6;
    ver[1].flow=100;
    ver[1].id=5;
    ver[2].flow=5798;
    ver[2].id=40;
    TComparatorF comp=*(flowset.begin());
    TComparatorI comp2=*(idset.begin());
    printf("%d %d\n",(*(comp.cmp)).flow,(*(comp2.cmp)).id);
    system("PAUSE");
    return 0;
}

I get

17 6

instead of

5798 40


回答1:


Answering the question "Is there a way to force my sets to update or a better idea for storing multiple sortings?"

Containers don't update themselves upon changes of their entries, that is why set entries and map keys are constant. You could make a wrapper of the sets where the update is done manually (remove/insert) or you could use boosts multi index containers which have this already (see the modifiers)



来源:https://stackoverflow.com/questions/19448058/how-to-update-set-of-pointers-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!