4 Replies - 7766 Views - Last Post: 21 February 2010 - 07:58 PM Rate Topic: -----

#1 elgose  Icon User is offline

  • D.I.C Head

Reputation: 102
  • View blog
  • Posts: 228
  • Joined: 03-December 09

C++ - Sorting 2D Char Array of C Strings

Posted 21 February 2010 - 03:55 PM

Hey all,

I am self-learning from "Starting Out with C++" (Tony Gaddis), but have come upon a problem I can't seem to solve. Hopefully, it's an easy one!

I have a char array of strings (names in the style of "Last, First") that is hard-coded that I need to sort using selection sort. I'm having difficulty getting it to run:


#include <cstring>

//.........
//I -think- this is the problem area:

void selSortChars(char array[], int size, int num_char) //array is array[size][num_char]
{
    int startScan, minIndex;
    char minVal[num_char];

    for (startScan = 0; startScan < (size - 1); startScan++)
    {
        minIndex = startScan;
        strcpy(minVal, array[startScan]);

        for (int index = startScan + 1; index < size; index++)
        {
            if( (strcmp(array[index], minVal)) < 0)
            {
                strcpy(minVal, array[index]);
                minIndex = index;
            }
        }

        strcpy(array[minIndex], array[startScan]);
        strcpy(array[startScan], minVal);
    }
}



Any tips/guidance is appreciated! I'm guessing it's I'm not understanding how to properly use strcmp and strcpy when dealing with char arrays?

Here is the entire code I'm trying to run incase it's an error somewhere else:
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;


// **************************************************** /
//
//           Begin Function Prototypes
//
// **************************************************** /

void selSortChars(char [], int, int);


// **************************************************** /
//
//            Begin Main Function
//
// **************************************************** /

int main()
{
    const int NUM_NAMES = 20, SIZE = 17;
    char names[NUM_NAMES][SIZE] = {"Collins, Bill", "Smith, Bart", "Allen, Jim",
                                    "Griffin, Jim", "Stamey, Marty", "Rose, Geri",
                                    "Tarylor, Terri", "Johnson, Jill",
                                    "Allison, Jeff", "Looney, Joe", "Wolfe, Bill",
                                    "James, Jean", "Weaver, Jim", "Pore, Bob",
                                    "Rutherford, Greg", "Javens, Renee",
                                    "Harrison, Rose", "Setzer, Cathy",
                                    "Pike, Gordon", "Holland, Beth" };

    selSortChars(names, NUM_NAMES, SIZE);


    //Display all chars to test if sorted
    for (int i = 0; i < SIZE; i++)
    {
        cout << names[i] << endl;
    }


    return 0;
}




// **************************************************** /
//
//            Begin Function Definitions
//
// **************************************************** /


void selSortChars(char array[], int size, int num_char) //array is array[size][num_char]
{
    int startScan, minIndex;
    char minVal[num_char];

    for (startScan = 0; startScan < (size - 1); startScan++)
    {
        minIndex = startScan;
        strcpy(minVal, array[startScan]);

        for (int index = startScan + 1; index < size; index++)
        {
            if( (strcmp(array[index], minVal)) < 0)
            {
                strcpy(minVal, array[index]);
                minIndex = index;
            }
        }

        strcpy(array[minIndex], array[startScan]);
        strcpy(array[startScan], minVal);
    }
}



Is This A Good Question/Topic? 0
  • +

Replies To: C++ - Sorting 2D Char Array of C Strings

#2 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 971
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: C++ - Sorting 2D Char Array of C Strings

Posted 21 February 2010 - 05:03 PM

Here's your code slightly modified: :)

#include <iostream>
#include <string>

using namespace std;

const int NUM_NAMES = 20, SIZE = 17; // moved make global

void selSortChars(char [][SIZE], int, int); // 2D array

int _tmain(int argc, _TCHAR* argv[])
{
	char names[NUM_NAMES][SIZE] = { // changed only because I prefer  :)/>
		"Collins, Bill", 
		"Smith, Bart",
		"Allen, Jim",
		"Griffin, Jim", 
		"Stamey, Marty",
		"Rose, Geri",
		"Tarylor, Terri", 
		"Johnson, Jill",
		"Allison, Jeff", 
		"Looney, Joe",
                "Wolfe, Bill",
		"James, Jean",
		"Weaver, Jim", 
		"Pore, Bob",
		"Rutherford, Greg", 
		"Javens, Renee",
		"Harrison, Rose", 
		"Setzer, Cathy",
		"Pike, Gordon", 
		"Holland, Beth" };

	selSortChars(names, NUM_NAMES, SIZE); 

	//Display all chars to test if sorted
//	for (int i = 0; i < SIZE; i++)
	for (int i = 0; i < NUM_NAMES; i++)
	{
		cout << names[i] << endl;
	}

	system("pause");
	return 0;
}
// **************************************************** /
//
//            Begin Function Definitions
//
// **************************************************** /

// changed array declaration to 2D
void selSortChars(char array[][SIZE], int size, int num_char) //array is array[size][num_char]
{
	int startScan, minIndex;

	char minVal[SIZE];  // need constant SIZE, num_char won't work

	for (startScan = 0; startScan < (size - 1); startScan++)
	{
		minIndex = startScan;
		strcpy(minVal, array[startScan]);

		for (int index = startScan + 1; index < size; index++)
		{
			if( (strcmp(array[index], minVal)) < 0)
			{
				strcpy(minVal, array[index]);
				minIndex = index;
			}
		}

		strcpy(array[minIndex], array[startScan]);
		strcpy(array[startScan], minVal);
	}
}



Your strcmp() strcpy usage is ok. The above code produces this as output:

Quote

Allen, Jim
Allison, Jeff
Collins, Bill
Griffin, Jim
Harrison, Rose
Holland, Beth
James, Jean
Javens, Renee
Johnson, Jill
Looney, Joe
Pike, Gordon
Pore, Bob
Rose, Geri
Rutherford, Greg
Setzer, Cathy
Smith, Bart
Stamey, Marty
Tarylor, Terri
Weaver, Jim
Wolfe, Bill
Press any key to continue . . .

This post has been edited by n8wxs: 21 February 2010 - 05:13 PM

Was This Post Helpful? 1
  • +
  • -

#3 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5643
  • View blog
  • Posts: 12,359
  • Joined: 16-October 07

Re: C++ - Sorting 2D Char Array of C Strings

Posted 21 February 2010 - 05:56 PM

If you're going to sort, swap pointers, not copy strings:

#include <iostream>
#include <cstring>

using std::cout;
using std::endl;

void sortNames(char *names[], int size) {
	for (int startScan = 0; startScan <size-1; startScan++) {
		int minIndex = startScan;
		for (int index = startScan + 1; index < size; index++) {
			if( (strcmp(names[index], names[minIndex])) < 0) {
				minIndex = index;
			}
		}
		if (minIndex != startScan) {
			char *temp = names[startScan];
			names[startScan] = names[minIndex];
			names[minIndex] = temp;
		}
	}
}

void showNames(char *names[], int size) {
	for (int i=0; i <size; i++) {
		cout << names[i] << endl;
	}
}

int main() {
	char *names[] = {"Collins, Bill", "Smith, Bart", "Allen, Jim",
		"Griffin, Jim", "Stamey, Marty", "Rose, Geri","Tarylor, Terri", "Johnson, Jill",
		"Allison, Jeff", "Looney, Joe", "Wolfe, Bill","James, Jean", "Weaver, Jim", "Pore, Bob",
		"Rutherford, Greg", "Javens, Renee","Harrison, Rose", "Setzer, Cathy",
		"Pike, Gordon", "Holland, Beth" };

	int size = sizeof(names)/sizeof(char *);
	showNames(names, size);
	sortNames(names, size);
	cout << endl << "Sorted" << endl;
	showNames(names, size);
	return 0;
}




If you're going to use C++, use string instead of char arrays. Also, most of the time, use container classes like vector instead of arrays.
Was This Post Helpful? 1
  • +
  • -

#4 elgose  Icon User is offline

  • D.I.C Head

Reputation: 102
  • View blog
  • Posts: 228
  • Joined: 03-December 09

Re: C++ - Sorting 2D Char Array of C Strings

Posted 21 February 2010 - 07:14 PM

Thanks for the help! I had a bit of a hiatus when I started up school again (no programming related classes yet, so it was easy to stop practicing) and I was afraid I'd be making all kinds of silly mistakes like passing a 2D array without writing it that way! :P

Here's what my latest guy is looking like:

#include <iostream>
#include <cstring>
using std::cout;
using std::endl;


// **************************************************** /
//
//           Begin Function Prototypes
//
// **************************************************** /

void selSortChars(char [][17], const int, const int);
//DUH! I'm passing a 2D array, so need to make sure it's setup that way
//Instead of making global variables, and since the two ints here
//aren't ever changed I decided just to make them const int's

// **************************************************** /
//
//            Begin Main Function
//
// **************************************************** /

int main()
{
    const int NUM_NAMES = 20, SIZE = 17;
    char names[NUM_NAMES][SIZE] = {"Collins, Bill", //Hey, this does look better!
                                    "Smith, Bart",
                                    "Allen, Jim",
                                    "Griffin, Jim",
                                    "Stamey, Marty",
                                    "Rose, Geri",
                                    "Tarylor, Terri",
                                    "Johnson, Jill",
                                    "Allison, Jeff",
                                    "Looney, Joe",
                                    "Wolfe, Bill",
                                    "James, Jean",
                                    "Weaver, Jim",
                                    "Pore, Bob",
                                    "Rutherford, Greg",
                                    "Javens, Renee",
                                    "Harrison, Rose",
                                    "Setzer, Cathy",
                                    "Pike, Gordon",
                                    "Holland, Beth" };


    selSortChars(names, NUM_NAMES, SIZE);


    //Display all chars to test if sorted
    for (int i = 0; i < NUM_NAMES; i++) //NUM_NAMES instead of SIZE, silly mistake!
    {
        cout << names[i] << endl;
    }


    return 0;
}




// **************************************************** /
//
//            Begin Function Definitions
//
// **************************************************** /


void selSortChars(char array[][17], const int size, const int num_char) //array is array[size][num_char] - and being passed as 2D now
{
    int startScan, minIndex;
    char minVal[num_char];

    for (startScan = 0; startScan < (size - 1); startScan++)
    {
        minIndex = startScan;
        strcpy(minVal, array[startScan]);

        for (int index = startScan + 1; index < size; index++)
        {
            if( (strcmp(array[index], minVal)) < 0)
            {
                strcpy(minVal, array[index]);
                minIndex = index;
            }
        }

        strcpy(array[minIndex], array[startScan]);
        strcpy(array[startScan], minVal);
    }
}



Quote

If you're going to sort, swap pointers, not copy strings:

Pointers is actually the chapter following sorting/searching alg's. I know the concept, but not how to implement it (or read it, so not sure what you did with the code). What you said makes perfect sense though, I'll come back to this after the next chapter to give it a go.


Quote

If you're going to use C++, use string instead of char arrays. Also, most of the time, use container classes like vector instead of arrays.

I've played around with strings in a couple problems (but my book uses char arrays exclusively spare 1 chapter, and C++ strings in the "Alternate Edition" of the book) and actually prefer vectors (although the book uses arrays almost exclusively). I have to admit - strings and vectors seem a lot easier to use, code with and manipulate.

As a beginner, do you think it's best to work with char arrays instead of strings, and arrays instead of vectors, just so I develop the understanding of how they work incase I encounter them in the future? Or is it best to become more comfortable with vectors and strings now and worry about it later?
Was This Post Helpful? 0
  • +
  • -

#5 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5643
  • View blog
  • Posts: 12,359
  • Joined: 16-October 07

Re: C++ - Sorting 2D Char Array of C Strings

Posted 21 February 2010 - 07:58 PM

View Postelgose, on 21 February 2010 - 08:14 PM, said:

As a beginner, do you think it's best to work with char arrays instead of strings, and arrays instead of vectors, just so I develop the understanding of how they work incase I encounter them in the future? Or is it best to become more comfortable with vectors and strings now and worry about it later?


Arrays are fundamental building blocks. They are an important concept. You're using them properly, as a statically sized list.

There are "strings" and there are "arrays of characters". In the C language, they are basically the same thing. In C++, std::string is a string, an array of characters is an array. It's considered a good practice to use C++ standard library when you can.

Nothing you learn while programming is a wasted effort. There is no "gee, I should have focused on that more." If anything, an understanding of the basics gives you a better foundation for when the computer does the work for you. C++ has a number of built in sorting methods, for example. However, it's still felt that understand how to write your own implementation has value.

Just program as much as possible, understanding of the best solution comes with experience. Have fun.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1