在 C++ 中的向量中查找元素索引
本文将介绍几种在 C++ 中如何在向量中查找元素索引的方法。
在 C++ 中使用自定义函数查找向量中的元素索引
我们可以使用自定义线性搜索功能在 vector
中找到给定元素的位置。请注意,这是解决此问题的一种非常无效的方法。在下面的示例代码中,我们声明一个整数的向量,并寻找一个任意的元素位置,如果调用成功,则将其输出。
#include <iostream>#include <string>#include <vector>using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
int findIndex(const vector<int> &arr, int item) {
for (auto i = 0; i < arr.size(); ++i) {
if (arr[i] == item)
return i;
}
return -1;
}
int main(int argc, char *argv[]) {
vector<int> arr = {1,2,3,4,5,6,7,8,9,10};
auto pos = findIndex(arr, 32);
pos != -1 ?
cout << "Found the element " << 32 << " at position " << pos << endl :
cout << "Could not found the element " << 32 << " in vector" << endl;
exit(EXIT_SUCCESS);
}
输出:
Could not found the element 32 in vector
在 C++ 中使用 std::find
算法查找向量中的元素索引
另外,我们可以使用 STL 库中的 std::find
算法。此函数将迭代器返回到满足条件的第一个元素。另一方面,如果未找到任何元素,则算法将返回范围的最后一个元素。请注意,返回的迭代器应按 begin
迭代器递减以计算位置。
#include <iostream>#include <string>#include <vector>using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
int findIndex2(const vector<int> &arr, int item) {
auto ret = std::find(arr.begin(), arr.end(), item);
if (ret != arr.end())
return ret - arr.begin();
return -1;
}
int main(int argc, char *argv[]) {
vector<int> arr = {1,2,3,4,5,6,7,8,9,10};
auto pos2 = findIndex2(arr, 10);
pos2 != -1 ?
cout << "Found the element " << 10 << " at position " << pos2 << endl :
cout << "Could not found the element " << 10 << " in vector" << endl;
exit(EXIT_SUCCESS);
}
输出:
Found the element 10 at position 9
在 C++ 中使用 std::find_if
算法查找向量中的元素索引
查找元素索引的另一种方法是调用 std::find_if
算法。它与 std::find
相似,除了第三个参数可以是用于评估每个迭代元素的谓词表达式。如果表达式返回 true,则算法将返回。注意,我们将 lambda 表达式作为第三个参数传递,该表达式检查元素是否等于 10
。
#include <iostream>#include <string>#include <vector>using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
int main(int argc, char *argv[]) {
vector<int> arr = {1,2,3,4,5,6,7,8,9,10};
auto ret = std::find_if(arr.begin(), arr.end(),
[](int x) { return x == 10; });
if (ret != arr.end())
cout << "Found the element " << 10 << " at position "
<< ret - arr.begin() << endl;
exit(EXIT_SUCCESS);
}
输出:
Found the element 10 at position 9
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。