找到所选对象的索引

时间:2016-10-13 18:41:28

标签: c++ indexing grouping selecteditem c++03

给定一个具有方法Foo的对象bool isChecked() const。我们说Foo foos[]

我保证只有foos的一个元素会在true上返回isChecked(),其他所有元素都会返回false

我正在寻找一种聪明的C ++ 03方法来查找true元素的索引。我可以做到这一点,但它非常丑陋。有没有人有更好的东西?

distance(foos, find_if(foos, foos + SIZE, mem_fun_ref(&Foo::isChecked)))
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>

using namespace std;

#define SIZE 42

class Foo{
    bool checked;
public:
    Foo() : checked(false) {}
    void setChecked() { checked = true; }
    bool isChecked() const { return checked; }
};

int main() {
    Foo foos[SIZE] = {};

    foos[13].setChecked();

    cout << distance(foos, find_if(foos, foos + SIZE, mem_fun_ref(&Foo::isChecked))) << endl;
}

Live Example

1 个答案:

答案 0 :(得分:0)

不幸的是,我的答案并不聪明,更重要的是可能不适合您的用例。但我会创建一个类(或结构)来保存你的Foo容器并保留索引。您必须存储一个额外的int(或索引所需的任何类型),但不必计算有效对象的位置。

例如类似的东西(或任何类型的容器符合您的要求或模板,如果您不仅要将其用于Foo ..):

class Foos {
private:
    int _index = -1;
    Foo _foos[MAXSIZE] = {};
public:
    Foos(int size, int index)
    {
      ....
    }
    int getIndex()
    {
        return _index;
    }
};

//...
//   then just call getIndex() when needed