簡體   English   中英

返回 bool 作為 cpp 中 bool operator[] 中的值

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

所以基本上我有一個包含布爾值(true,false)的std :: vector容器,我需要一個operator [],但是當我返回具有正確索引的值(bool)時,它給了我一個錯誤this: 無法將“bool&”類型的非 const 左值引用綁定到“bool”類型的右值|

我的操作員看起來像這樣:

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;
}

以及給出錯誤的調用:

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

@Jarod42 的回答稍有改善:

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");
}

並假設所有內部向量的大小相同:

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];
}

std::vector 可能是特殊的,具有打包優化(因此它的operator[]返回包裝器/代理類)。

然后您可以轉發返回值:

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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM