我有一个小的未排序数组,我想找到特定值的索引.C++是否具有内置的顺序搜索功能,或者您是否只是在每次出现时自己编写循环?
我特意使用C风格的数组,如:
std::string arr[5] = { "EVEN", "ODD", "NONE", "MARK", "SPACE" };
Run Code Online (Sandbox Code Playgroud)
我需要用户提供的值的索引.
Mic*_*urr 10
std::find() 应该管用:
#include <stdio.h>
#include <algorithm>
#include <string>
using std::string;
std::string arr[5] = { "EVEN", "ODD", "NONE", "MARK", "SPACE" };
int main() {
string* pArrEnd = arr + sizeof( arr)/sizeof(arr[0]);
string* pFound = std::find( arr, pArrEnd, "MARK");
if (pFound == pArrEnd) {
printf( "not found\n");
}
else {
printf( "%s was found at index %d\n", pFound->c_str(), pFound - arr);
printf( "or using STL: %d\n", std::distance( arr, pFound));
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您可以在STL容器以外的容器上使用STL算法.例如,你可以在C风格的数组中使用std :: find():
// alloc the array
static const size_t numItems = 100000;
int * items = new int[numItems];
// fill the array
for( size_t n = 0; n < numItems; ++n )
items[n] = n;
// find 42 using std::find()
int* found = std::find(&items[0], &items[numItems], 42);
if( found == &items[numItems] )
{
// this is one past the end, so 42 was not found
items[0] = 42;
}
else
{
// we found the first instance of 42 at this location
// change it to 43
*found = 43;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2483 次 |
| 最近记录: |