Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ String array sorting

Tags:

I am having so much trouble trying to figure out the sort function from the C++ library and trying to sort this array of strings from a-z , help please!!

I was told to use this but I cant figure out what I am doing wrong.

// std::sort(stringarray.begin(), stringarray.end());

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
  int z = 0;
  string name[] = {"john", "bobby", "dear", 
                   "test1", "catherine", "nomi", 
                   "shinta", "martin", "abe", 
                   "may", "zeno", "zack", "angeal", "gabby"};

  sort(name[0],name[z]);

  for(int y = 0; y < z; y++)
  {
    cout << name[z] << endl;
  }
  return 0;
}
like image 547
ssj3goku878 Avatar asked Aug 17 '13 19:08

ssj3goku878


People also ask

How do you sort an array of strings?

To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them.

Can we sort string in C?

C Sort String in Ascending Order Receive any string using gets() function. Get the length of string using strlen() function of string. h library and initialize it to any variable say len. Now create a for loop that runs from 0 to one less than the string length.

How do you arrange an array of strings in ascending order?

It means that the array sorts elements in the ascending order by using the sort() method, after that the reverseOrder() method reverses the natural ordering, and we get the sorted array in descending order. Syntax: public static <T> Comparator<T> reverseOrder()

Can we sort char array in C?

Yes. That is definitely possible. You could know that just by writing some sample code, such as this: char charArray[] = {'A','Z', 'K', 'L' }; size_t arraySize = sizeof(charArray)/sizeof(*charArray); std::sort(charArray, charArray+arraySize); //print charArray : it will print all chars in ascending order.


3 Answers

The algorithms use iterator to the beginning and past the end of the sequence. That is, you want to call std::sort() something like this:

std::sort(std::begin(name), std::end(name)); 

In case you don't use C++11 and you don't have std::begin() and std::end(), they are easy to define yourself (obviously not in namespace std):

template <typename T, std::size_t Size> T* begin(T (&array)[Size]) {     return array; } template <typename T, std::size_t Size> T* end(T (&array)[Size]) {     return array + Size; } 
like image 172
Dietmar Kühl Avatar answered Oct 21 '22 22:10

Dietmar Kühl


int z = sizeof(name)/sizeof(name[0]); //Get the array size

sort(name,name+z); //Use the start and end like this

for(int y = 0; y < z; y++){
    cout << name[y] << endl;
}

Edit :

Considering all "proper" naming conventions (as per comments) :

int N = sizeof(name)/sizeof(name[0]); //Get the array size

sort(name,name+N); //Use the start and end like this

for(int i = 0; i < N; i++){
    cout << name[i] << endl;
}

Note: Dietmar Kühl's answer is best in all respect, std::begin() & std::end() should be used for std::sort like functions with C++11, else they can be defined.

like image 36
P0W Avatar answered Oct 21 '22 20:10

P0W


Example using std::vector

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

int main()
{
    /// Initilaize vector using intitializer list ( requires C++11 )
    std::vector<std::string> names = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};

    // Sort names using std::sort
    std::sort(names.begin(), names.end() );

    // Print using range-based and const auto& for ( both requires C++11 )
    for(const auto& currentName : names)
    {
        std::cout << currentName << std::endl;
    }

    //... or by using your orignal for loop ( vector support [] the same way as plain arrays )
    for(int y = 0; y < names.size(); y++)
    {
       std:: cout << names[y] << std::endl; // you were outputting name[z], but only increasing y, thereby only outputting element z ( 14 )
    }
    return 0;

}

http://ideone.com/Q9Ew2l

This completely avoids using plain arrays, and lets you use the std::sort function. You might need to update you compiler to use the = {...} You can instead add them by using vector.push_back("name")

like image 26
olevegard Avatar answered Oct 21 '22 20:10

olevegard