I have an array of ints. How to create an iterator for it that will sort every x element in the array?
I would like to use std::sort.
template<class T>
class SomeClass
{
private:
    int intArray[100];
};
I have an array of ints. How to create an iterator for it that will sort every x element in the array?
I would like to use std::sort.
template<class T>
class SomeClass
{
private:
    int intArray[100];
};
For arrays their iterators are pointers to their elements.
You can use standard generic functions std::begin and std::end declared in the header <iterator> to get a range of iterators.
So for example to sort the array defined in the class you can use standard algorithm std::sort. For example
template<class T>
class SomeClass
{
public:
    void sort()
    {
        std::sort( std::begin( intArray ), std::end( intArray ) );
    }
    template <typename Comparison>
    void sort( Comparison comp )
    {
        std::sort( std::begin( intArray ), std::end( intArray ), comp );
    }
private:
    int intArray[100];
};
 
    
    If you meant of providing iterators to the SomeClass class, you can as follows:
#include <iostream>
#include <algorithm>// std::sort
#include <iterator> // std::begin. std::end
template<class T>
class SomeClass
{
private:
    int intArray[10]{ 2, 3, 1, 4, 5, 7, 6, 8, 9, 10 };
    // or fill the array as per
public:
    // provide begin() and end() iterators
    auto begin()->decltype(std::begin(intArray)) { return std::begin(intArray); }
    auto end()->decltype(std::end(intArray)) { return std::end(intArray); }
    // or since C++14, no trailing return is needed!
    // auto begin() { return std::begin(intArray); }
    // auto end() { return std::end(intArray); }
};
int main()
{
    SomeClass<int> obj;
    // now you can apply `std::sort` like this
    std::sort(obj.begin(), obj.end());
    // also you can iterate using range based for - loop
    for (const auto ele : obj) std::cout << ele << " ";
    return 0;
}
 
    
    int myArray[] = {32,71,12,45,26,80,53,33};
std::vector<int> myvector (myArray, myArray+8); // 32 71 12 45 26 80 53 33
// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33
//OR use the below line for myArray[100] it will work fine
std::sort(std::begin(myArray), std::end(myArray));
I hope the above code may help to answer your question. I am using a default array, however you can freely use myArray[100] and add the values from user or randomly.
