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

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

#include <vector>

#include <algorithm>

#include <string>

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_INFO_STRU> task_vector;

    vector<TASK_INFO_STRU>::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 <iostream>     // std::cout

#include <algorithm>    // std::find

#include <vector>       // 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/

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值