2

I want to write a C++ generic algorithm that can work on set, list, map, vector, etc... So this algorithm accepts a container and a function object, so I can check for certain conditions.

This algorithm needs to check the longest series in the container according to a certain condition and return its length.

i am having trouble in passing the function object to the function as i get this error (in the second line in main) :

"Multiple markers at this line - Invalid arguments ' Candidates are: void functionA(#0 &, #0 &, #1) ' - invalid initialization of non-const reference of type 'int*&' from an rvalue of type 'std::array::iterator {aka "

i don't understand the problem since there is an operator () , in the function object :\ even if i call the constructor first i still get this error ..

what i tried :

template<typename T,typename Predicate>
void functionA(T& it1 , T& end1,Predicate pred){
    for(;it1 != end1; ++it1){
        T it2=it1++;
        if(!pred(*it1,*it2)){
            std::cout << *it1 << "\n" ;
            return;
        }
        }
    std::cout <<"not found" << "\n" ;
}

class FindFirst {
    public:
    FindFirst();
    bool operator()(int f , int s) const {
       return f < s;
    }
};

int main() {

    std::array<int,11> myarray = {1,2,4,7,10,14,3,6,12,24,48};
    functionA(myarray.begin(),myarray.end(),find);

}
0

1 Answer 1

2

The problem is that std::array::begin returns by value, which is a temporary and can't be bound to lvalue reference to non-const (i.e. T&).

Change the parameter type of functionA to pass-by-value, e.g.

template<typename T,typename Predicate>
void functionA(T it1 , T end1,Predicate pred){

LIVE

Sign up to request clarification or add additional context in comments.

3 Comments

i get this error now : undefined reference to `FindFirst::FindFirst()'
@mamama You need to define it, the constructor. If you have nothing to implement you can just remove the declaration.
@mamama Congratulations; at least you got advances.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.