C++ find函数详解

C++ find函数详解

C++的find函数提供了一种对vector、string类型数据进行查找的方法。

首先是对vector的查找:


int main()
{
    vector<int> arr;
    arr.push_back(1);
    arr.push_back(5);
    arr.push_back(12);
    arr.push_back(7);
    arr.push_back(6);
    arr.push_back(4);

    //输出一下vector
    for(int i=0;i<arr.size();i++){
        cout<<arr[i]<<" ";
    }
    cout<<endl;

    vector<int>::iterator it;
    //使用find()对vector进行查找会返回一个迭代器
    it = find(arr.begin(), arr.end(), 7);

    if (it != arr.end()){ //若返回的迭代器不指向end,说明查到了元素
        cout << "输出查到的元素:" << *it<<endl;
        cout << "输出查到的元素的下标:" << it-arr.begin();
    }
    else
        cout << "查找失败";

    return 0;
}

输出结果:

1 5 12 7 6 4
输出查到的元素:7
输出查到的元素的下标:3

对字符串的查找:

int main()
{
    string s="98426357";
    cout<<"字符串为:"<<s<<endl;
    int pos0=s.find('9');
    cout<<"查到的下标:"<<pos0<<endl;
    int pos1=s.find('a');
    cout<<"未查到返回:"<<pos1<<endl;
    return 0;
}

输出结果:

字符串为:98426357
查到的下标:0
未查到返回:-1
  • 6
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值