关于查找类函数
顺序查找类
find(first, last, type) //找值
find_if(first, last, function) //找符合function()
下面两个可以理解是字符串匹配
find_end(first1, last1, first2, last2) //在1中找2最后出现的位置
find_first_of(first1, last1, first2, last2) //在1中找2首次出现的位置
二分查找类
要求容器是顺序存储 map 和 set 本身就是顺序的 vector 和 string 需要提前排序
lower_bound 第一个 num ≥ 的数值 返回迭代器
upper_bound 第一个 num > 的数值 返回迭代器
binary_search 单纯的二分查找 返回bool
常用容器find()使用举例
vector
void findVector()
{
vector<int>arr = {1,68,515,48,5,5,8,4,48,1,2};
auto it = find(arr.begin(), arr.end(), 5);
if (it != arr.end())
cout << *it << endl;
else
cout << "没找到" << endl;
int arr2[] = {1,68,515,48,5,5,8,4,48,1,2};
int n = sizeof(arr2)/sizeof(arr2[0]);
auto it2 = find(arr2, arr2+n, 100);
if (it2 != arr2+n)
cout << *it2 << endl;
else
cout << "没找到" << endl;
return ;
}
本代码输出: =我是分割线= 5 没找到 =我是分割线=
string
void findString()
{
string s = "Hello World!";
int pos;
pos = s.find('l');
if (pos != -1)
cout << pos << endl;
else
cout << "没找到" << endl;
pos = s.find('l', 5);
if (pos != -1)
cout << pos << endl;
else
cout << "没找到" << endl;
pos = s.find("ll");
if (pos != -1)
cout << pos << endl;
else
cout << "没找到" << endl;
return ;
}
本代码输出: =我是分割线= 2 9 2 =我是分割线=
stack和queue和priority_queue
没有迭代器
deque
void findDeque()
{
vector<int>arr = {1,68,515,48,5,5,8,4,48,1,2};
deque<int>dq(arr.begin(), arr.end());
auto it = find(dq.begin(), dq.end(), 66);
if (it != dq.end())
cout << *it << endl;
else
cout << "没找到" << endl;
return ;
}
本代码输出: =我是分割线= 没找到 =我是分割线=
list
void findList()
{
vector<int>arr = {1,68,515,48,5,5,8,4,48,1,2};
list<int>lst(arr.begin(), arr.end());
auto it = find(lst.begin(), lst.end(), 66);
if (it != lst.end())
cout << *it << endl;
else
cout << "没找到" << endl;
return ;
}
本代码输出: =我是分割线= 没找到 =我是分割线=
set
void findSet()
{
vector<int>arr = {1,68,515,48,5,5,8,4,48,1,2};
set<int>st(arr.begin(), arr.end());
auto it = st.find(8);
if (it != st.end())
cout << *it << endl;
else
cout << "没找到" << endl;
return ;
}
本代码输出: =我是分割线= 8 =我是分割线=
map
void findMap()
{
vector<int>arr = {1,68,515,48,5,5,8,4,48,1,2};
map<int, int>mp;
for (int i = 0; i < arr.size(); i++){
pair<int, int>pir(arr[i], i);
mp.insert(pir);
}
auto it = mp.find(8);
if (it != mp.end())
printf("mp[%d] = %d\n", it->first, it->second);
else
puts("没找到");
return ;
}
本代码输出: =我是分割线= mp[8] = 6 =我是分割线=
关于map中通过value找可以可以使用find_if()来实现,具体代码请看下面链接 C++ map 根据value找key
|