0

I am learning C++ and stuck with one scenario where I have to convert array to set

I have pointer which holds the address of array and I want to get all unique elements of array into set . Using STL how its possible . Below is my code spinet and am also looking for good explanation .

#include<set>

void possiblepermutation(int *array) {
    set<int> roots(begin(array),end(array));

} 

After reading below comment , I understood that as I am passing pointer so begin() and end() will have no idea about start and end . Can you help me what if I pass size of array along with array pointer , how to do.

void possiblepermutation(int *array , int n) {
        set<int> roots(begin(array),end(array)); // HOW TO THEN 

    } 
Sumeet Kumar Yadav
  • 11,912
  • 6
  • 43
  • 80

1 Answers1

2

std::begin and std::end do not return the ranges of an array that has decayed to a pointer type. All they see is a pointer. Informally, they don't know that the pointer actually points to the first element in an array.

It's your job to either pass a C++ standard library container like a std::vector to your function, perhaps by reference, or pass the length of the array as a parameter: for example

void possiblepermutation(int* array , std::size_t n){
    std::set<int> roots(array, array + n);
Bathsheba
  • 231,907
  • 34
  • 361
  • 483