1
  int arr[] = {0, 1, 15, 22, 100, 101, 232, 2323};
  int n = sizeof(arr) / sizeof(arr[0]);
  int x = 232;

  auto a = lower_bound(arr, arr + n, x) - arr;
  if (a < n && arr[a] == x) {
    // x found at index a
    cout << x << " is found " << "at index: " << a << endl;
  }

lower_bound returns an address of the element but if we subtract - arr from it, it dereferences the pointer. How come that happens?

CodeCrack
  • 5,253
  • 11
  • 44
  • 72

1 Answers1

5

arr is an array, and when an array is used in an expression, it can decay into a pointer. Since lower_bound returns a pointer (that's the iterator type for a raw array), and arr decays into a pointer, you are subtracting the address of the found object from the address of the start of the array which gives you the number of elements between them. There is no dereferencing happening at all.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402