14
A
回答
34
你有沒有爲你的功能沒有任何意義的語法(爲什麼會返回值有一個成員叫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);
0
如果數組排序,則需要使用 linear search。
2
10
這是一個非常簡單的方式通過做手工。正如Peter所說,你也可以使用<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;
}
2
#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數組創建它,然後使用相同的解決方案如在我的例子。
1
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();
+0
請爲您的答案添加一些解釋,以使其對其他讀者更有用。 – 2015-06-25 08:12:44
0
我們這裏使用簡單的線性搜索。首先將索引初始化爲-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;
}
相關問題
- 1. 如何搜索並返回多暗數組中的特定值?
- 2. Matlab:如何在向量中找到特定值的索引
- 3. 搜索多維數組並返回該數組中的特定值
- 4. 索引匹配,其中查找值在查找數組中
- 5. 數組檢測方法 - 返回特定子數組索引的值?
- 6. Javascript:如何查找第一個重複值並返回其索引?
- 7. 在列表中查找並返回位置索引處的值
- 8. C#如何搜索數組中的索引以找到值
- 9. 如何返回Object數組的索引?
- 10. 如何直接索引查找函數返回的數組
- 11. 將數組從特定索引排序到特定索引
- 12. 從布爾數組中返回一個索引值數組,其中true true
- 13. 找到數組中的第一個元素,其中塊返回true並返回塊的返回值
- 14. 如何查找數組中的特定索引
- 15. 如何在ruby的數組中找到整數/最大整數並返回索引位置?
- 16. 如何在特定情況下在數組中找到值?
- 17. 如何從源數組中搜索特定的索引值數組php
- 18. 返回索引從JSON返回數組
- 19. 在Matlab中查找未返回給定值的索引
- 20. PHP:找到一個數組中的值並返回一個找到的值
- 21. 如何在數組數組中找到元素的索引?
- 22. 比較數組中的索引值並返回一個新數組
- 23. JavaScript匹配一個數組的片段並返回索引值
- 24. 如何在多維$ _SESSION數組中找到特定值?
- 25. 如何在PHP數組中找到特定值
- 26. 爲什麼數組返回值與數組索引值?
- 27. 如何返回數組中的特定值? - Java
- 28. 在Python3/Numpy中過濾數組並返回索引
- 29. 如何找到數組中最大值的索引?
- 30. 如何找到數組的索引?
索引應該至少是一個無符號類型。 – GManNickG 2010-10-11 20:43:00
您確定要使用索引嗎?使用某種形式的迭代器可能會更簡潔。 – 2010-10-11 21:30:15
如果找不到搜索的值,您想要什麼樣的返回值? – Arun 2010-10-12 01:05:13