问题
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