C++ bootcamp · Lab 37

Linear search

mediumVectors12 minLesson: Vectors

Read the question, write C++ on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

The first number is n, then n integers, then a target.

Print the 0-based index of the first time the target appears, or -1 if it is missing.

Input. n, then n integers, then target.

Output. One integer: the index, or -1.

Constraints

  • 1 ≤ n ≤ 1000

Examples

Example 1
Input
5
3 1 8 2 4
8
Output
2
Example 2
Input
4
1 2 3 4
9
Output
-1
Hint
  1. std::find returns an iterator; subtract v.begin() for the index, or check against v.end().
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
  int n;
  std::cin >> n;
  std::vector<int> v(n);
  for (int i = 0; i < n; i++) std::cin >> v[i];
  int target;
  std::cin >> target;
  auto it = std::find(v.begin(), v.end(), target);
  std::cout << (it == v.end() ? -1 : (int)(it - v.begin())) << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.