使用一个函数对两个不同的向量(每个都具有"活动"bool)进行排序

0 c++ templates vector c++11

我创建了具有ACTIVE BOOL的基类

class BaseTest{
public:
    bool active = false;

    BaseTest(){
    // make most true
        if ( getRand(0, 5) != 2){
            active = true;
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

创建两个不同的子类

class ChildTest_1: public BaseTest{

    string child1 = "Is child 1";

public:

    ChildTest_1(){

    }
};

class ChildTest_2: public BaseTest{

    string child2 = "Is NOT child 1";

public:

    ChildTest_2(){

    }

};
Run Code Online (Sandbox Code Playgroud)

我希望能够将子(或带有"ACTIVE"的任何向量)传递给此函数,它将返回第一个非活动状态.我有一个程序,它运行许多对象的很多向量,并且通常有一个管理每个对象向量的类.在每个mgmt类中编写此循环正在变得痛苦和浪费重复的代码.我想要一个我可以传递任何具有活动var的对象的向量.

我现在不需要排序,但这是我所需要的最接近的术语.

我需要的是一个函数,我可以传递一个向量,它将返回第一个非活动对象;

如果它们不需要共享基类,只要向量中的每个对象都有自己的ACTIVE bool,那就更好了,但是我也可以创建一个简单的基类,它都可以从中派生出来.

int firstInactive(vector<BaseTest> & test ){

    for ( int cnt = 0 ; cnt < test.size() ; cnt++ ){

        if (!test[cnt].active){

            cout << cnt << " Is inactive " <<endl;

            // add actual sorting here if I need;

            return cnt;
         }

    }

}



int main(int, char const**){



    vector< ChildTest_1 > allTest1;

    vector< ChildTest_2 > allTest2;


    allTest1.resize(10);

    allTest2.resize(10);



    cout << "First inactive in alltest1 is " << firstInactive(allTest1) <<endl;

    cout << "First inactive in alltest2 is " << firstInactive(allTest2) <<endl;

// as expected it says no known matching function call.    

    return 0 ;

}
Run Code Online (Sandbox Code Playgroud)

我已经搜索并试验了几天了.我已经阅读了关于多态性和模板的所有内容,但找不到帮助我的示例.

Jar*_*d42 5

您可以使用模板(不需要基类):

template <typename T>
auto firstInactive(const std::vector<T>& v)
// -> typename std::vector<T>::const_iterator // for c++11
{
    return std::find_if(v.begin(), v.end(), [](const T& e) { return !e.active; });
}
Run Code Online (Sandbox Code Playgroud)

并称之为:

std::vector<ChildTest_1> allTest1(10);
std::vector<ChildTest_2> allTest2(10);

auto it1 = firstInactive(allTest1);
auto it2 = firstInactive(allTest2);

if (it1 != allTest1.end()) {
    std::cout << "First inactive in alltest1 is "
              << std::distance(allTest1.cbegin(), it1) << std::endl;
}
if (it2 != allTest2.end()) {
    std::cout << "First inactive in alltest2 is "
              << std::distance(allTest2.cbegin(), it2) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

演示