Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determine 2 arrays difference component in sort template function

Tags:

c++

templates

I have two arrays like this:

int iArr[] = {2, 34, -4, 2, 15, 0, 15};
Person pArr[] ={{"Nam", 23}, {"Hao", 18}, {"Phuong", 23}, {"Ha", 65}, {"Banh", 12}, {"Son", 25}};

and a function of bubble sort like this:

template <class T>
void bubble(T a[],int n)
{
    if ((typeid(a).name()).find("Person") != std::string::npos)
    {
        std::cout << "found!" << '\n';
    }
    int i,j,t;
    for(i=0;i<n;i++)
    {
        for(j=0;j<n-i-1;j++)
        {
            if(a[j]>a[j+1])
            {
                swapX(a[j], a[j+1]);
            }
        }
    }
}

How can I determine which array is passed to this function?

I have to sort iArr in ascending order, and pArr in descending order (by age).

like image 929
Giải Trí Cho Bé Avatar asked May 12 '26 19:05

Giải Trí Cho Bé


1 Answers

Just pass the template another argument telling it wether you want ascending or descending.

Alternatively, don't use a template. Write a function and overload it.

like image 115
Ivan Rubinson Avatar answered May 14 '26 07:05

Ivan Rubinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!