Frank
Frank

Reputation: 37

return bool as a value in bool operator[] in cpp

So basically i have an std::vector container that contains bool values (true, false), and i need an operator[] for it, but when i return the value(bool) with the right index, it gives me an error like this: cannot bind non-const lvalue reference of type 'bool&' to an rvalue of type 'bool'|

my operator looks like this:

bool& operator[] ( unsigned int idx) {
    typename std::vector<bool>::iterator retval;
    for (typename std::vector<std::vector<bool> *>::iterator it = data.begin(); it != data.end(); ++it) {
        for (typename std::vector<bool>::iterator cont_it = (*it)->begin(); cont_it != (*it)->end(); ++cont_it) {
            if (idx == 0) {
                retval = cont_it;
            }
            idx--;
        }
    }
    return *retval;
}

and the call what gives error:

ivb[0] = false;
ivb[1] = true;

Upvotes: 0

Views: 562

Answers (2)

Coral Kashri
Coral Kashri

Reputation: 3506

A little performances improve to @Jarod42 answer:

std::vector<bool>::reference operator[](unsigned int idx) {
    for (auto &inner : data) {
        if (idx < inner.size()) {
            return inner[idx];
        }
        idx -= inner.size();
    }
    throw std::runtime_error("out of range");
}

And assume all of the inner vectors are with the same size:

std::vector<bool>::reference operator[](unsigned int idx) {
    // vectors_sizes = data[0].size()
    if (idx >= vectors_sizes * data.size())
        throw std::runtime_error("out of range");
    return data[idx / vectors_sizes][idx % vectors_sizes];
}

Upvotes: 1

Jarod42
Jarod42

Reputation: 217145

std::vector might be special, with packing optimization (so its operator[] return wrapper/proxy class).

You might then forward the return value:

std::vector<bool>::reference operator[] ( unsigned int idx) { 
    for (auto& inner : data) {
        for (auto&& e : inner) {
            if (idx-- == 0) {
                return e;
            }
        }     
    }
    throw std::runtime_error("out of range");
}

Upvotes: 0

Related Questions