vector 查找/查找和对比结构体元素值

原地转:http://www.cplusplus.com/reference/algorithm/find_if/
#include

#include

#include

#include

using namespace std;

 

typedef struct

{

    string str1;

    string str2;

    string str3;

}TASK_INFO_STRU;

 

bool findx(TASK_INFO_STRU &task)

{

    return task.str2 == "task_two";

}

 

int main()

{

    vector task_vector;

    vector::iterator iter;

 

    TASK_INFO_STRU task;

 

    task.str1 = "1";

    task.str2 = "task_one";

    task.str3 = "fine";

    task_vector.push_back(task);

 

    task.str1 = "2";

    task.str2 = "task_two";

    task.str3 = "fine";

    task_vector.push_back(task);

 

    iter = find_if(task_vector.begin(), task_vector.end(), findx);

    if (iter != task_vector.end())

    {

        cout << iter->str2 << endl;

        task_vector.erase(iter);

    }

 

    iter = find_if(task_vector.begin(), task_vector.end(), findx);

    if (iter != task_vector.end())

    {

        cout << iter->str2 << endl;

    }

 

    return 0;

}

 


#include      // std::cout

#include     // std::find

#include        // std::vector

bool IsOdd (int i) {

  return ((i%2)==1);

}

int main()

{

    int p[] = {0, 1, 2, 3, 4, 5};

    std::vector<int> myvector( p, p + 6 );

    std::vector<int>::iterator it;

    /** @brief find() example */

    // iterator to vector element:

    it = find( myvector.begin(), myvector.end(), 3 );

    if( it != myvector.end() ) // finded

    {

        std::cout << "The element 3 is found." << '\n';

        // now *it is 3. it is a iterator to int.

        ++it;

        std::cout << "The element following 3 is " << *it << '\n';

    }

    /** @brief find_if() example */

    // iterator to vector element matching some condition.

    it = std::find_if (myvector.begin(), myvector.end(), IsOdd);

    if( it != myvector.end() ) // finded

    {

        std::cout << "The first odd value is " << *it << '\n';

    }

    return 0;

}

find(first, last, val) 查找值为val的元素,返回迭代器

http://www.cplusplus.com/reference/algorithm/find/

find_if(first,last, pred) 查找符合某个条件的元素,返回迭代器

http://www.cplusplus.com/reference/algorithm/find_if/

你可能感兴趣的:(基础知识储备,vector,顺序容器)