Sorting an array using template(c++)

Pocky Is God

Ars Legatus Legionis
24,457
Three arrays:

Code:
int a[6] = { 44, 55 , 22, 88, 33, 11 };
    std::string  months[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
    char vowels[5] = { 'E','U','I', 'A', 'O'};

Was trying to repurpose my display template call, and sort gives me compiler errors.

Code:
template <typename T, size_t size> 

void displayArray(const T(&array)[size])
{
    
    for (size_t i = 0; i < size; ++i)
    std::cout << array[i] <<  " " << std::endl;;
}


Assignment wants me to display using template above (done) but then display again using standard sort and I cannot get it to work. Any help is appreciated.
 

ComradeXavier

Ars Scholae Palatinae
881
Subscriptor++
You'll need to remove the const qualifier to get the sort to work.
Code:
std::sort( const_cast< T * >( array ), const_cast< T * >( array + size ) );
Removing const with const_cast is almost always a bad idea.

For example:
Code:
#include <iostream>

int main(int argc, char* argv[]) {
    const int x = 1;
    const_cast<int&>(x) = 0;
    std::cout << x << std::endl;
    return 0;
}
This program, as compiled, will generally print 1, not 0. Because x is declared const, the compiler is not required to generate code that will "notice" changes to the value, even if there is an intervening assignment.

If const is the reason you're having trouble changing your function template, omit it from the parameter declaration:

Code:
template <typename T, size_t size>
void sortArray(T(&array)[size]) {
    std::sort(&array[0], &array[size]);
}
 

Pocky Is God

Ars Legatus Legionis
24,457
You'll need to remove the const qualifier to get the sort to work.
Code:
std::sort( const_cast< T * >( array ), const_cast< T * >( array + size ) );
Removing const with const_cast is almost always a bad idea.

For example:
Code:
#include <iostream>

int main(int argc, char* argv[]) {
    const int x = 1;
    const_cast<int&>(x) = 0;
    std::cout << x << std::endl;
    return 0;
}
This program, as compiled, will generally print 1, not 0. Because x is declared const, the compiler is not required to generate code that will "notice" changes to the value, even if there is an intervening assignment.

If const is the reason you're having trouble changing your function template, omit it from the parameter declaration:

Code:
template <typename T, size_t size>
void sortArray(T(&array)[size]) {
    std::sort(&array[0], &array[size]);
}


Thanks everyone. Can someone explain to me why the CONST was the one causing me grief? If not, I appreciate the help regardless.
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
Thanks everyone. Can someone explain to me why the CONST was the one causing me grief? If not, I appreciate the help regardless.

Sorting an array means modifying its contents (by swapping them around) - if the array is declared const, then the elements cannot be modified.

g++, as is its custom, vomits up several hundred error messages (because templates) that boil down to "we don't have a version of swap for const types".
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
You'll need to remove the const qualifier to get the sort to work.
Code:
std::sort( const_cast< T * >( array ), const_cast< T * >( array + size ) );
Removing const with const_cast is almost always a bad idea.

For example:
Code:
#include <iostream>

int main(int argc, char* argv[]) {
    const int x = 1;
    const_cast<int&>(x) = 0;
    std::cout << x << std::endl;
    return 0;
}
This program, as compiled, will generally print 1, not 0. Because x is declared const, the compiler is not required to generate code that will "notice" changes to the value, even if there is an intervening assignment.

If const is the reason you're having trouble changing your function template, omit it from the parameter declaration:

Code:
template <typename T, size_t size>
void sortArray(T(&array)[size]) {
    std::sort(&array[0], &array[size]);
}

Yeah, that was actually the first thing I posted, but then for some reason I got it in my head that he needed to sort the array as part of the display function - if that's not the case, then this is the correct approach.
 

Jonathon

Ars Legatus Legionis
17,644
Subscriptor
You'll need to remove the const qualifier to get the sort to work.
Code:
std::sort( const_cast< T * >( array ), const_cast< T * >( array + size ) );
Removing const with const_cast is almost always a bad idea.

For example:
Code:
#include <iostream>

int main(int argc, char* argv[]) {
    const int x = 1;
    const_cast<int&>(x) = 0;
    std::cout << x << std::endl;
    return 0;
}
This program, as compiled, will generally print 1, not 0. Because x is declared const, the compiler is not required to generate code that will "notice" changes to the value, even if there is an intervening assignment.

If const is the reason you're having trouble changing your function template, omit it from the parameter declaration:

Code:
template <typename T, size_t size>
void sortArray(T(&array)[size]) {
    std::sort(&array[0], &array[size]);
}

Yeah, that was actually the first thing I posted, but then for some reason I got it in my head that he needed to sort the array as part of the display function - if that's not the case, then this is the correct approach.
Even if that were the case, const_cast is still a bad idea. If you can't change the function definition to remove the const, you can't sort the array in place-- you'd need to copy it and sort the copy instead.

(Declaring a function parameter as const is a promise to the caller that you're not going to mutate the passed value. From the compiler's point of view, this means that any optimizations it made under the assumption of const-ness are now going to generate incorrect code, plus, from an API consumer's point of view (even assuming a compiler that's smart enough to tolerate these kinds of shenanigans), you're now mutating something you said you wouldn't and, as array is passed by reference here, the caller would see those changes.)
 

Lt_Storm

Ars Tribunus Angusticlavius
21,343
Subscriptor++
(Declaring a function parameter as const is a promise to the caller that you're not going to mutate the passed value. From the compiler's point of view, this means that any optimizations it made under the assumption of const-ness are now going to generate incorrect code, plus, from an API consumer's point of view (even assuming a compiler that's smart dumb enough to tolerate these kinds of shenanigans), you're now mutating something you said you wouldn't and, as array is passed by reference here, the caller would see those changes.)

FTFY
 

Pocky Is God

Ars Legatus Legionis
24,457
Out of curiosity, what are you guys developing on? I have a home PC that I have dual booted with Windows 10 and PopOS, I try and keep most of my development work in PopOS, but I have a not so small hard on for MSVS, but am wanting a laptop for class. Was thinking of getting a Macbook since I get a discount through work, but was also looking System76 laptops as well.

I anticipate doing mostly c++ work, but also want to do projects in Python. I have Sublime Text in Pop working great, and would probably use the same in MacOs.
 

Jonathon

Ars Legatus Legionis
17,644
Subscriptor
Out of curiosity, what are you guys developing on? I have a home PC that I have dual booted with Windows 10 and PopOS, I try and keep most of my development work in PopOS, but I have a not so small hard on for MSVS, but am wanting a laptop for class. Was thinking of getting a Macbook since I get a discount through work, but was also looking System76 laptops as well.

I anticipate doing mostly c++ work, but also want to do projects in Python. I have Sublime Text in Pop working great, and would probably use the same in MacOs.
My main work machine's a 16" MacBook Pro; I do a mix of work targeted to Windows and *nix, with most of the Windows work happening on a desktop that I remote into from the MBP (I don't think it even has a monitor hooked up to it). Also have a couple Windows VMs available locally on the MBP that I use as needed (work for some specific clients doesn't leave my MBP because the Windows desktop doesn't have full disk encryption turned on).

I don't do a ton of C++ work these days, though. Most of my day-to-day work right now is Node + Typescript or Python (mostly targeted to Mac/Linux); we also have a fairly large mixed mostly-C#/some-C++ codebase but I'm not personally doing much in that space right now.
 

ComradeXavier

Ars Scholae Palatinae
881
Subscriptor++
Almost missed an assignment due today at 1. First actual usage for school that requires certain style guides applied.

WHERE THE HELL ARE MY CURLY BRACKETS??!?#$^%&^@!
Can you set up clang-format (or similar, possibly in your editor of choice) to apply the school's style rules? I find if I can make formatting happen automatically, i'm no longer annoyed when it's not necessarily my preferred style.
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
Out of curiosity, what are you guys developing on?

At work, Amazon Linux AMIs (basically Red Hat), accessed via PuTTy sessions in a Windows 10-based Amazon Workspace, running on a Macbook. vi for editing (everyone else uses emacs, but I can't internalize all the key combos). If I'm feeling especially ornery I'll log in from a Mac terminal window, but that requires several extra ssh's. Pretty much the only thing I do in the Windows workspace is run the terminal sessions - on very rare occasions I'll fire up Postman or SoapUI for development or troubleshooting (the AMIs and Windows workspace are in a preprod environment that can talk to our customer systems, the Macbook isn't). Everything else (Slack, Outlook, Word, Excel, etc.) runs directly on the Mac.

At home, I have an Ubuntu box that I play around on. What little programming I do on the Mac itself is just stupid little command-line shit to think through a problem or play with a concept.
 

Lt_Storm

Ars Tribunus Angusticlavius
21,343
Subscriptor++
Out of curiosity, what are you guys developing on?

At work, Amazon Linux AMIs (basically Red Hat), accessed via PuTTy sessions in a Windows 10-based Amazon Workspace, running on a Macbook. vi for editing (everyone else uses emacs, but I can't internalize all the key combos). If I'm feeling especially ornery I'll log in from a Mac terminal window, but that requires several extra ssh's. Pretty much the only thing I do in the Windows workspace is run the terminal sessions - on very rare occasions I'll fire up Postman or SoapUI for development or troubleshooting (the AMIs and Windows workspace are in a preprod environment that can talk to our customer systems, the Macbook isn't). Everything else (Slack, Outlook, Word, Excel, etc.) runs directly on the Mac.

At home, I have an Ubuntu box that I play around on. What little programming I do on the Mac itself is just stupid little command-line shit to think through a problem or play with a concept.

If everyone else is using Emacs and you like Vi, might I suggest EVIL? It does provide the best of both worlds.