使用 search_n 函数查找向量元素的索引
Find index of vector element using search_n function
我需要使用算法库中的函数查找向量元素的索引。
示例:
{1,2,3,4,5,6,7,8,9,10}
在第 5 个位置找到元素 5。
#include <algorithm>
#include <iostream>
#include <vector>
bool comp(int a, int b) { return a < b; }
int main() {
int n = 10;
std::vector<int> a{10, 8, 5, 4, 1, 2, 3, 6, 7, 9};
sort(a.begin(), a.begin() + n, comp);
int number = 5;
std::vector<int>::iterator it;
it = std::search_n(a.begin(), a.begin() + n, number);
if (it != a.end())
std::cout << "found at position " << (it - a.begin()) << '\n';
else
std::cout << "match not found\n";
return 0;
}
我收到错误(在第 11 行):
no matching function for call to ‘search_n(std::vector::iterator, __gnu_cxx::__normal_iterator >, int&)’
你能解释一下这里的问题是什么吗?
std::search_n
函数查找范围内特定值出现指定次数的 序列 ;该数字是第三个参数(this cppreference page 上的 count
)。
所以,如果你坚持为此使用std::search_n
,你将需要添加一个额外的参数(count
,这将是1
) 在你的通话中:
it = std::search_n(a.begin(), a.begin() + n, 1, number);
但是,在查找单个值时,使用 search_n
有点矫枉过正;最好使用更简单(更快)的 std::find
function。此外,您可以使用更简单明了的 a.end()
.
代替 a.begin() + n
it = std::find(a.begin(), a.end(), number);
另请注意,C++ 中的索引和迭代器位置从 零 开始,因此,将上述修复应用于您的代码后,答案将是“找到位置4";如果你想要一个基于 1 的位置,那么将 1
添加到该位置。
我需要使用算法库中的函数查找向量元素的索引。
示例:
{1,2,3,4,5,6,7,8,9,10}
在第 5 个位置找到元素 5。
#include <algorithm>
#include <iostream>
#include <vector>
bool comp(int a, int b) { return a < b; }
int main() {
int n = 10;
std::vector<int> a{10, 8, 5, 4, 1, 2, 3, 6, 7, 9};
sort(a.begin(), a.begin() + n, comp);
int number = 5;
std::vector<int>::iterator it;
it = std::search_n(a.begin(), a.begin() + n, number);
if (it != a.end())
std::cout << "found at position " << (it - a.begin()) << '\n';
else
std::cout << "match not found\n";
return 0;
}
我收到错误(在第 11 行):
no matching function for call to ‘search_n(std::vector::iterator, __gnu_cxx::__normal_iterator >, int&)’
你能解释一下这里的问题是什么吗?
std::search_n
函数查找范围内特定值出现指定次数的 序列 ;该数字是第三个参数(this cppreference page 上的 count
)。
所以,如果你坚持为此使用std::search_n
,你将需要添加一个额外的参数(count
,这将是1
) 在你的通话中:
it = std::search_n(a.begin(), a.begin() + n, 1, number);
但是,在查找单个值时,使用 search_n
有点矫枉过正;最好使用更简单(更快)的 std::find
function。此外,您可以使用更简单明了的 a.end()
.
a.begin() + n
it = std::find(a.begin(), a.end(), number);
另请注意,C++ 中的索引和迭代器位置从 零 开始,因此,将上述修复应用于您的代码后,答案将是“找到位置4";如果你想要一个基于 1 的位置,那么将 1
添加到该位置。