Hi, i've got a list with nodes with this structure:

private:
    char namefield[30];
    char tam[3];
    char type[1];
};

i want to find and element with the find function from alghorithm class but i want to do it with the namefield property of the item, the find function has an item to find as a parameter but the thing is that i want to send a property of the node instead of the node itself..

As mentioned by tinstaafl, you can do it std::find_if. To do this you will need a function that returns true when you hit the element that you want. Say your struct is called A and has a member x:

struct A { int x; };

You need to define a comparator to find the value of, say, x during the find:

int main
{
    std::vector< A > v(5);

    // Add some items to the vector
    int i = -2;
    for ( std::vector< A >::iterator it = v.begin(), it != v.end(); ++it, ++i )
        it->x = i;

    // A functor class to find an element with an x of a given value
    struct x_is_equal_to
    {
        int _x;

        x_is_equal_to( int x ) : _x( x ) {}

        bool operator()( const A& a ) const { return a.x == _x; }
    };

    // Use STL find_if with the functor to find the right x value
    std::vector< A >::const_iterator it_find = std::find_if( v.begin(), v.end(), x_is_equal_to( 1 ) );
    std::cout << "Found element with x = " << it_find->x << std::endl;
}

You can also do this with a function instead of a functor, in conjunction with one of the std::bind classes:

/// Function to compare the x-value of an A with the value passed in
bool x_is_equal_to( const A& a, const int x ) { return a.x == x; }

int main
{
    std::vector< A > v(5);

    // Add some items to the vector
    int i = -2;
    for ( std::vector< A >::iterator it = v.begin(), it != v.end(); ++it, ++i )
        it->x = i;

    // Use STL find_if with the function and std::bind2nd to find the target x value
    std::vector< A >::const_iterator it_find = std::find_if( v.begin(), v.end(),
        std::bind2nd( x_is_equal_to, 1 ) );

    std::cout << "Found element with x = " << it_find->x << std::endl;
}

If you're using a compiler that's compliant with C++11, then you can use a lambda expression to do this job (if the feature is available, then I think it's preferable):

int main
{
    std::vector< A > v(5);

    // Add some items to the vector
    int i = -2;
    for ( std::vector< A >::iterator it = v.begin(), it != v.end(); ++it, ++i )
        it->x = i;

    // Use STL find_if with the function and std::bind2nd to find the right x value
    const int target_x_value = 1;
    std::vector< A >::const_iterator it_find = std::find_if( v.begin(), v.end(),
        [ target_x_value ]( const A& a ) { return a.x == target_x_value; } );

    std::cout << "Found element with x = " << it_find->x << std::endl;
}

Hope that helps a bit.

This article has been dead for over six months. Start a new discussion instead.