Originally Posted by
Elysia
what do you intend for the OP to use memcmp for?
if (s)he does not want to use a predefined sort algriumthim....errr spelling
but instead make his/her own. memcmp is an easy way to do it
Code:
#include <iostream>
#include <string>
//This function will output 10 elements to the user.
void output_array_to_user(std::string * pointer){
int x = 10;
std::cout << "Output: ";
do{
std::cout << pointer->c_str() << " ";
x--;
pointer++;
}while( x );
std::cout << std::endl;
}
//This function will swap elements in the array
void swap_array_elements( std::string* a, std::string* b){
std::string tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
int main(int argc, char* argv){
/*This is our array of words that will be sorted.
This could easly be ANY type of data */
std::string words[10] =
{ "apples", "are", "fun", "to", "eat", "and", "keep", "the", "doctor", "away" };
//Display array to user
output_array_to_user( words );
//These loops will sort the array.
for( int x = 0; x < 10; x++ ){
for( int y = 0; y < 10; y++){
//When comparing two different words, size matters.
//Always remimber not to compare more than is there.
if( words[x].size() == words[y].size() ){
if( memcmp(words[y].c_str(), words[x].c_str(), words[x].size() ) > 0 )
swap_array_elements( &words[x], &words[y] );
}
if( words[x].size() > words[y].size() ){
if( memcmp(words[y].c_str(), words[x].c_str(), words[y].size() ) > 0 )
swap_array_elements( &words[x], &words[y] );
}
if( words[x].size() < words[y].size() ){
if( memcmp(words[y].c_str(), words[x].c_str(), words[x].size() ) > 0 )
swap_array_elements( &words[x], &words[y] );
}
}
}
output_array_to_user( words );
return 0;
}