查找所选对象的索引 [英] Find the Index of the Selected Object

查看:130
本文介绍了查找所选对象的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我保证 foos 将在 isChecked()上返回 true ,所有其他将返回 false

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

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

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

推荐答案

更重要的是可能不适合你的用例。但我会做一个类(或结构)保存你的Foo容器和保持索引。你必须存储一个额外的int(或任何你需要的索引类型),但不必计算有效对象的位置。

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.

例如类似的东西(或者无论哪种类型的容器符合你的要求,或者如果你不想使用Foo ..):

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

这篇关于查找所选对象的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆