[英]How do I find a particular value in an array and return its index?
偽代碼:
int arr[ 5 ] = { 4, 1, 3, 2, 6 }, x;
x = find(3).arr ;
x 然后會返回 2。
你在函數中使用的語法沒有意義(為什么返回值有一個名為arr
的成員?)。
要查找索引,請使用<algorithm>
標頭中的std::distance
和std::find
。
int x = std::distance(arr, std::find(arr, arr + 5, 3));
或者你可以把它變成一個更通用的功能:
template <typename Iter>
size_t index_of(Iter first, Iter last, typename const std::iterator_traits<Iter>::value_type& x)
{
size_t i = 0;
while (first != last && *first != x)
++first, ++i;
return i;
}
在這里,如果找不到值,我將返回序列的長度(這與STL算法返回最后一個迭代器的方式一致)。 根據您的喜好,您可能希望使用其他形式的故障報告。
在你的情況下,你會像這樣使用它:
size_t x = index_of(arr, arr + 5, 3);
這是一種非常簡單的手工操作方法。 彼得建議你也可以使用<algorithm>
。
#include <iostream>
int find(int arr[], int len, int seek)
{
for (int i = 0; i < len; ++i)
{
if (arr[i] == seek) return i;
}
return -1;
}
int main()
{
int arr[ 5 ] = { 4, 1, 3, 2, 6 };
int x = find(arr,5,3);
std::cout << x << std::endl;
}
花哨的答案。 使用std :: vector並使用std :: find進行搜索
簡單的答案
使用for循環
#include <vector>
#include <algorithm>
int main()
{
int arr[5] = {4, 1, 3, 2, 6};
int x = -1;
std::vector<int> testVector(arr, arr + sizeof(arr) / sizeof(int) );
std::vector<int>::iterator it = std::find(testVector.begin(), testVector.end(), 3);
if (it != testVector.end())
{
x = it - testVector.begin();
}
return 0;
}
或者你可以以正常方式構建一個向量,而不是從一個int數組創建它,然后使用我的例子中所示的相同解決方案。
int arr[5] = {4, 1, 3, 2, 6};
vector<int> vec;
int i =0;
int no_to_be_found;
cin >> no_to_be_found;
while(i != 4)
{
vec.push_back(arr[i]);
i++;
}
cout << find(vec.begin(),vec.end(),no_to_be_found) - vec.begin();
我們這里只使用線性搜索。 首先將索引初始化為-1。 然后搜索數組,如果找到則在索引變量中指定索引值並中斷。 否則,index = -1。
int find(int arr[], int n, int key)
{
int index = -1;
for(int i=0; i<n; i++)
{
if(arr[i]==key)
{
index=i;
break;
}
}
return index;
}
int main()
{
int arr[ 5 ] = { 4, 1, 3, 2, 6 };
int n = sizeof(arr)/sizeof(arr[0]);
int x = find(arr ,n, 3);
cout<<x<<endl;
return 0;
}
有一個find(...) function 用於查找數組中的元素,該元素返回指向該元素的迭代器。 如果未找到該元素,則迭代器指向數組末尾。
如果找到元素,我們可以簡單地計算迭代器與數組開頭的距離,以獲得該元素的索引。
using namespace std;
int arr[ 5 ] = { 4, 1, 3, 2, 6 }
auto it = arr.find(begin(arr), end(arr), 3)
if(it != end(arr))
cerr << "Found at index: " << (it-begin(arr)) << endl;
else
cerr << "Not found\n";
如果數組未排序,則需要使用線性搜索 。
您可以使用提供的 STL 算法庫的查找功能
#include <iostream>
#include <algorithm>
using std::iostream;
using std::find;
int main() {
int length = 10;
int arr[length] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int* found_pos = find(arr, arr + length, 5);
if(found_pos != (arr + length)) {
// found
cout << "Found: " << *found_pos << endl;
}
else {
// not found
cout << "Not Found." << endl;
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.