Find the Index of the Selected Object

我只是一个虾纸丫 提交于 2019-12-11 06:44:52

问题


Given an object Foo which has the method bool isChecked() const. Let's say that I have Foo foos[].

I am guaranteed that exactly one element of foos will return true on isChecked(), all others will return false.

I'm looking for a clever C++03 way to find the index of the true element. I can do this but it's pretty ugly. Does anyone have something better?

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:


Unfortunately my answer is not clever, and more importantly may not fit your use case(s). But I would make a class (or struct) which hold your Foo container and keep the index. You have to store an extra int (or whichever type you need for an index) but won't have to calculate the position of the valid object.

For instance something like that (or with whichever type of container fits your requirements or with template if you want to use it not only for 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


来源:https://stackoverflow.com/questions/40028595/find-the-index-of-the-selected-object

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