0

**The code I tried to implement is : **

#include<iostream>
using namespace std;

int main()
{
   int n, k;
   cout << "Enter the number of elements: \n";
   cin >> n;

   cout << "Enter the array: \n";
   int *arr = new int[n];
   for (int i = 0; i < n; i++)
        cin >> arr[i];

   cout << "Enter k: " << endl;
   cin >> k;

   cout << "Elements less than k: " << endl;
   for (int x : arr)
   {
       if (x < k)
            cout << x << endl;
   }

   
   delete[] arr;

   return 0;
}

**The error it's throwing is :** error: 'begin' was not declared in this scope for (int x : arr) ^

The array is dynamically allocated. Takes elements and var 'k' as input and ideally returns the elements which are less than k. first loop is traditional for loop second one is range based, and the problem is in that

I tried taking reference '&x' in there to but the problem persists

problem :

error: 'begin' was not declared in this scope
    for (int x : arr)
                 ^
5
  • arr is a pointer. It is not an array. There is no "size information" associated with a pointer -- it is just a pointer, no more, no less. Commented Dec 28, 2023 at 9:58
  • 1
    You are probably looking for std::vector for arr. Commented Dec 28, 2023 at 9:59
  • 1
    int *arr = new int[n]; --> std::vector<int> arr(n); Commented Dec 28, 2023 at 10:00
  • For range based for loops to work the type you loop over must have a begin() and end() method that return iterators to the begin and end of your container. As you can see you only have an int* and that has no way of nowing what its "end" is, it is just a pointer into memory. That's why people tell you to use std::vector, it solves multiple things : you will have no new/delete needed (new/delete hardly ever should appear in current C++ code), You will not have an owning raw pointer (also not recommmended in C++) and you will get your begin() and end() from std::vector Commented Dec 28, 2023 at 10:11

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.