查找第一次出现/不出现指定对象的位置:lower_bound()与upper_bound()
2013-09-21 21:29
381 查看
可以利用lower_bound()成员函数查找向量容器中第一次出现某个对象的位置;upper_bound()成员函数查找向量容器中第一次不出现某个对象的位置。
#include
"stdafx.h"
#include
<iostream>
#include
<vector>
#include
<algorithm>
using namespace std;
int_tmain(int argc, _TCHAR* argv[])
{
vector<int> vecInt;
for(int i=0; i<8;++i)
{
vecInt.push_back(i);
}
vector<int>::iterator whereIt;
whereIt= lower_bound(vecInt.begin(),vecInt.end(),4);//查找第一次出现的位置
cout<<"元素之后的元素:"<<endl;
copy(whereIt,vecInt.end(),ostream_iterator<int>(cout,""));
//输出之后的元素
whereIt= upper_bound(vecInt.begin(),vecInt.end(),0);//查找第一次不出现的位置
cout<<"\n第一次不出现的位置之后的元素:"<<endl;
copy(whereIt,vecInt.end(),ostream_iterator<int>(cout,""));
//输出之后的元素
return 0;
}
执行结果:
#include
"stdafx.h"
#include
<iostream>
#include
<vector>
#include
<algorithm>
using namespace std;
int_tmain(int argc, _TCHAR* argv[])
{
vector<int> vecInt;
for(int i=0; i<8;++i)
{
vecInt.push_back(i);
}
vector<int>::iterator whereIt;
whereIt= lower_bound(vecInt.begin(),vecInt.end(),4);//查找第一次出现的位置
cout<<"元素之后的元素:"<<endl;
copy(whereIt,vecInt.end(),ostream_iterator<int>(cout,""));
//输出之后的元素
whereIt= upper_bound(vecInt.begin(),vecInt.end(),0);//查找第一次不出现的位置
cout<<"\n第一次不出现的位置之后的元素:"<<endl;
copy(whereIt,vecInt.end(),ostream_iterator<int>(cout,""));
//输出之后的元素
return 0;
}
执行结果:
相关文章推荐
- 查找指定字符串在字符串中第一次或最后一词出现的位置
- Java查找指定字符串第一次或最后一次出现的位置
- 对于一个有序数组,我们通常采用二分查找的方式来定位某一元素,请编写二分查找的算法,在数组中查找指定元素。 给定一个整数数组A及它的大小n,同时给定要查找的元素val,请返回它在数组中的位置(从0开始),若不存在该元素,返回-1。若该元素出现多次,请返回第一次出现的位置。
- C++算法库学习__std::sort__对 vector进行排序_排序后就可以进行使用std::lower_bound进行二分查找(查找第一个大于等于指定值的迭代器的位置)__std::unique
- C++算法库学习__std::sort__对 vector进行排序_排序后就可以进行使用std::lower_bound进行二分查找(查找第一个大于等于指定值的迭代器的位置)__std::unique
- JavaSE8基础 String indexOf 正向 从指定索引值开始查找 字符在字符串中第一次出现的位置
- indexOf() 如何判断一个元素在指定数组中是否存在? 找出指定元素出现的所有位置? indexOf()方法 是正序查找,lastIndexOf()是倒叙查找
- STL之二分查找(binary_search(),lower_bound(),upper_bound() )
- c++ 二分查找的函数 lower_bound & upper_bound & binary_search
- 查找一个short标记数值在二进制文件中第一次出现的位置
- STL中的二分查找——lower_bound 、upper_bound 、binary_search
- 算法---查找子串第一次出现的位置索引(indexOf)
- 在相邻元素相差1的数组中查找某一特定元素第一次出现的位置(非遍历)
- 二分查找第一次出现的位置
- STL中的multimap---顺便说说如何查找同一关键字对应的所有值(利用count, lower_bound/upper_bound, equal_range)
- STL中的二分查找——lower_bound 、upper_bound 、binary_search
- 在相邻元素相差1的数组中查找某一特定元素第一次出现的位置
- STL 二分查找三兄弟(lower_bound(),upper_bound(),binary_search())
- STL 二分查找 upper_bound和lower_bound用法
- 从一个字符串中提取子字符串 /字符串的逆置/查找字符第一次出现的位置