1.5. Алгоритм find

Следующая программа показывает, как мы можем находить требуемое зна­чение в векторе:

// findl.cpp: Найти заданное значение в векторе. #include <iostream> #include <vector> #include <algorithm> using namespace std;

int mainO

{ vector<int> v;

int x;

cout « "Enter positive integers, followed by 0:\n";

while (cin >> x, x != 0) v.push_back(x);

cout « "Value to be searched for: ";

cin >> x;

vector<int>::iterator i =

find(v.begin(), v.end(), x) ; if (i == v.end())

cout  «   "Not  found\n"; else {    cout  «   "Found";

if   (i  == v.begin())

cout  «   "   as  the  first  element";

else  cout <<   "   after   "   <<  *--i; }

cout << endl; return 0; }

АлгоритмУгга/ применим к каждому из четырех последовательных контейнеров (вектор, двусторонняя очередь, список и массив). Если мы везде заменим vector на deque, поведение программы не изменится, как и в случае, если мы заменим vector на list. Версия для массива целочисленных значений приведена ниже:

// find2.cpp: Найти заданное значение в массиве. #include <iostream> #include <algorithm> using namespace std;

int main()

{ int a[10], x, n = 0;

cout « "Enter at most 10 positive integers, "

"followed by 0:\n"; while (cin » x, x != 0 && n < 10) a[n++] = x; cout « "Value to be searched for: "; cin » x;

int *p = find(a, a+n, x); if (p == a+n)

cout « "Not found\n"; else { cout « "Found";

if (P == a)

cout « " as the first element";

else cout « " after " « *--p; }

cout « endl; return 0;


<< назад вперед >>