Есть ли в C ++ функция последовательного поиска? - PullRequest
1 голос
/ 26 марта 2009

У меня есть небольшой несортированный массив, и я хотел бы найти index определенного значения. Есть ли в C ++ встроенная функция последовательного поиска для этого, или вы просто пишете цикл каждый раз, когда он появляется?

Я специально использую массив в стиле C, например:

std::string arr[5] = { "EVEN", "ODD", "NONE", "MARK", "SPACE" };

и мне нужен индекс значения, предоставленного пользователем.

Ответы [ 5 ]

15 голосов
/ 26 марта 2009

Используйте std::find() из библиотеки STL- -библиотека или find() -метод вашего конкретного контейнера.

10 голосов
/ 26 марта 2009

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;
}
5 голосов
/ 26 марта 2009

Вы можете использовать алгоритмы STL для контейнеров, отличных от контейнеров STL. Например, вы можете использовать std :: find () в массиве в стиле C:

// 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;
}
4 голосов
/ 26 марта 2009

Полагаю, вам нужен индекс, а не итератор.

int main()
{
    // for c++ vector
    typedef int Element;
    typedef std::vector<Element> CppVector;

    CppVector v;
    v.push_back( 2 );
    v.push_back( 4 );
    v.push_back( 8 );
    v.push_back( 6 );

    const Element el = 4;

    CppVector::const_iterator it = std::find( v.begin(), v.end(), el );
    if ( it == v.end() )
    {
        std::cout << "there is no such element" << std::endl;
    }
    else
    {
        const CppVector::size_type index = it - v.begin();
        std::cout << "index = " << index << std::endl;
    }

    // for C array
    typedef Element CVector[4];
    CVector cv;
    cv[0] = 2;
    cv[1] = 4;
    cv[2] = 8;
    cv[3] = 6;

    const std::size_t cvSize = sizeof( cv ) / sizeof( Element );

    std::cout << "c vector size = " << cvSize << std::endl;

    const Element* cit = std::find( cv, cv + cvSize, el );
    const std::size_t index = cit - cv;

    if ( index >= cvSize )
        std::cout << "there is no such element" << std::endl;
    else
        std::cout << "index = " << index << std::endl;
}
3 голосов
/ 26 марта 2009

В дополнение к уже упомянутой возможности STL (std::find) есть функция POSIX lsearch (с семантикой c).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...