简体   繁体   中英

make_heap not making heaps

I have a program that heapsorts a subset of another vector in a vector, as references to indices.

std::vector<foo> knowledgeBase;
std::vector<int> workingSet;

Does this comparison class work?

class Compare
{
    bool operator()(int lft, int rgt)
    {
        return knowledgeBase[lft].bar() > knowledgeBase[rgt].bar();
    }
};

Compare is a nested class within the class that contains knowledgeBase, so I have access to the variables, but the index referring to the smallest value is never returned by workingSet.front();

What am I doing wrong? I can post more code if required, (which has further, unrelated bugs that I can't test for because this doesn't work) but I know for certain that my make_heap is not creating the heap that I want.

In case I'm doing something really stupid, my make_heap call is as follows:

std::make_heap(workingSet.begin(), workingSet.end(), Compare());

Edit: bar is size() of a std::set internal to foo. This set is not empty, nor is it undefined, because I can output its contents (and verify them as correct). Though that is using an iterator... is that not sufficient?

Edit2: Upon further research, I found that bar() was always returning 1. I added an int, and incremented that every time I added a variable, like so...

foo::foo()
{
    siz = 0;
}

void foo::addLiteral(std::string var, bool truth)
{
    literals.insert(Literal(var,truth)); 
    ++siz;
}

class foo()
{
public:
    foo();
    void addLiteral(std::string var, bool truth);
    bool bar(){return siz;}
private:
    int siz;
    std::set<Literal, LiteralComp> literals;
}

foo is initialized like so:

...
   foo newClause;
    ss.str(input);
    ss >> variable;
    while(!ss.fail())
    {
        if(variable[0] == '~')
        {
            variable = variable.substr(1);
            truth = false;
        }
        else truth = true;
        newClause.addLiteral(variable, truth);
        ss >> variable;
    }
    knowledgeBase.push_back(newClause);
workingSet.push_back(count++);
...

And foo.size() still always returns 1.

What is going on?

I realize this is far out of the scope of my main question, and there are pieces not defined in the code I've given, but I've been working at this problem for six or so hours now and still have no idea what's going on.

... I feel dumb now.

class foo()
{
public:
    foo();
    void addLiteral(std::string var, bool truth);
    bool bar(){return siz;} <==== returns a bool
private:
    int siz;
    std::set<Literal, LiteralComp> literals;
}

Sorry for wasting anyone's time.

You didn't forget to size your working set did you? For example, using reserve and then operator[] won't increase the actual size of the vector and so make_heap will no-op.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM