代码之家  ›  专栏  ›  技术社区  ›  Jonathan Mee

查找选定对象的索引

  •  1
  • Jonathan Mee  · 技术社区  · 9 年前

    给定对象 Foo 哪个有方法 bool isChecked() const .让我们说我有 Foo foos[] .

    我保证 foos 会回来的 true 在…上 isChecked() 所有其他人都会回来 false .

    我正在寻找一种聪明的C++03方法来查找 真的 要素我可以这样做,但很难看。有人有更好的吗?

    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 回复  |  直到 9 年前
        1
  •  0
  •   call me Steve    9 年前

    不幸的是,我的答案并不聪明,更重要的是可能不适合您的用例。但我会创建一个类(或结构),它保存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