I'm a pretty new person to c++ so i'm kinda having some trouble with this problem.
im using functions to sort out a sentence inputted by the user into ascending and descending order. i keep getting the error that n is undefined but i'm not sure where i'm going wrong.
Second, why do you have 'n' on those places that give the error? What value is supposed to be in the 'n'? Do you know that std::string has member function size()?
See http://www.cplusplus.com/reference/string/string/size/
The compiler error (and warning) messages do state the line number of the issue.
First, n isn't visible in those functions, which is why you're getting an error. Second, std::string tracks it's own length, so what's the point of it?
You can get the length of a std::string named list by calling std::string::size() or (if you prefer) std::string::length(): list.size();
Also - line 46 declares a char named temp which is never used. It is never used because that name is shadowed by another variable also named temp within an inner scope on line 51. You should delete it. Plus, the standard library provides a swap() function, too: std::swap(list[i], list[j]);.
I did end up seeing that the temp was declared as two different types and fixed that, the bubble sort function was given to me by my teacher, and we haven't gone over the swap function yet.
string bubble_sort(string list)
{
// the 'list' has your data
char temp;
string line;
// the 'line' is empty and thus line.length() == 0
for ( int i = 0; i< line.length(); ++i ) {
// 0<0 is false and the outer loop does thus 0 iterations
// these lines are not executed
for ( int j = i + 1; j < line.size(); ++j ) {
if ( list[j] < list[i] ) {
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
// nothing has changed the 'list'
return list;
}
Lets go back and use that n:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
string bubble_sort( string list )
{
constint n = ????.size(); // whose size?
char temp;
for (int i = 0; i < n; ++i ) {
for (int j = i + 1; j < n; ++j ) {
if ( list[j] < list[i] ){
int temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
return list;
}