C++ String array sorting

123,257

Solution 1

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.

Solution 2

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;
}

Solution 3

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")

Solution 4

Your loop does not do anything because your counter z is 0 (and 0 < 0 evaluates to false, so the loop never starts).

Instead, if you have access to C++11 (and you really should aim for that!) try to use iterators, e.g. by using the non-member function std::begin() and std::end(), and a range-for loop to display the result:

#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(begin(name),end(name));

    for(auto n: name){
         cout << n << endl;
    }
    return 0;    
}

Live example.

Solution 5

This works for me:

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

using namespace std;

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

    int sname = sizeof(name)/sizeof(name[0]);

    sort(name, name + sname);

    for(int i = 0; i < sname; ++i)
        cout << name[i] << endl;

    return 0;
}
Share:
123,257

Related videos on Youtube

ssj3goku878
Author by

ssj3goku878

Updated on July 09, 2022

Comments

  • ssj3goku878
    ssj3goku878 almost 2 years

    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;
    }
    
    • olevegard
      olevegard almost 11 years
      Use a std::vector instead of a plain array
    • ssj3goku878
      ssj3goku878 almost 11 years
      Can you show an example please? I am kinda new to C++
    • Admin
      Admin almost 11 years
      Use qsort() on a separate list of pointers to your strings.
    • Dietmar Kühl
      Dietmar Kühl almost 11 years
      @Mattingly: Why would anybody want to use a substantially slower and a lot harder to use approach to sorting?
    • Admin
      Admin almost 11 years
      I suppose the question was fairly STL specific... yet I prefer to avoid STL like the plague.
    • TemplateRex
      TemplateRex almost 11 years
      @Mattingly might as well code in C then
    • juanchopanza
      juanchopanza almost 11 years
      @Mattingly not STL specific. Just C++, which means the C++ standard library too.
    • Lightness Races in Orbit
      Lightness Races in Orbit almost 11 years
      @Mattingly: Avoiding the STL is extremely easy. The C++ Standard Library not so much. If that's what you actually meant, why are you avoiding it "like the plague"? That seems really strange. What is your good reason for this?
    • Admin
      Admin almost 11 years
      @LightnessRacesinOrbit: Yes, that's what I meant... thanks for the correction.
    • Admin
      Admin almost 11 years
      @DietmarKühl: You should probably do some profiling and get some hard results before making claims. With a quick test, a qsort implementation ran 3-6x faster than the std version, on the provided example. Code and results provided in an answer below.
    • Dietmar Kühl
      Dietmar Kühl almost 11 years
      @Mattingly: I posted a corresponding response with what I would call improved measurements, trying to be fair to both std::sort() and qsort(): Adding the memory management in the case of using std::sort() but not when using qsort() seems unreasonable. Also, I didn't claim that constructing and std::sort()ing is faster than just just qsort()ing. It came as a surprise, however, that the naive approach to sorting isn't faster using std::sort() on larger data sets (although it compares two different things: sorting an array of std::strings and sorting an array of char const*s).
    • Dietmar Kühl
      Dietmar Kühl almost 11 years
      @Mattingly: Following a comment from Mooing Duck I moved the response to my blog.
    • Lightness Races in Orbit
      Lightness Races in Orbit almost 11 years
      @Mattingly: Why are you avoiding it "like the plague"? That seems really strange. What is your good reason for this?
  • TemplateRex
    TemplateRex almost 11 years
    for the love of future programmers: at the very least, rename z to N and y to i, so that it at least resembles all other code using index manipulations...
  • juanchopanza
    juanchopanza almost 11 years
    This is a good answer, but it would be better to use const references in the range based for loop instead of copying the strings.
  • olevegard
    olevegard almost 11 years
    @juanchopanza I agree, I just used auto for simplicity. Also I wasn't entirely sure what it would evaluate to in this case.
  • juanchopanza
    juanchopanza almost 11 years
    It would evaluate to std::string, so you could use for(const auto& currentName : names) to get const std::string& and avoid the copies.
  • olevegard
    olevegard almost 11 years
    @juanchopanza Okay, thanks. I was thinkging it could evalutate to std::vector<std::string>::iterator guess I'm not that famililar with C++11 yet. Updated my answer to use const &
  • Lightness Races in Orbit
    Lightness Races in Orbit almost 11 years
    Please don't get array sizes like that.
  • Lightness Races in Orbit
    Lightness Races in Orbit almost 11 years
    You don't get warnings about the deprecated conversions between char const* and char*? String literals are immutable. I also wouldn't accept that magic number in a code review.
  • Lightness Races in Orbit
    Lightness Races in Orbit almost 11 years
    (In fact, the deprecated conversion was removed in C++11, making this program ill-formed!)
  • László Papp
    László Papp almost 11 years
    @TemplateRex, for the love of future programmers, at the very least, do not use "N". I renamed it to sname yesterday, and also 'y' to 'i'. Did you like my reply then? :)
  • László Papp
    László Papp almost 11 years
    @Lightness Races in Orbit: pardon ?
  • TemplateRex
    TemplateRex almost 11 years
    @LaszloPapp I made the comment here because this answer is the accepted one, and promotes an off-beat naming convention that -while not technically wrong, of course- is just making it harder to read
  • László Papp
    László Papp almost 11 years
    @TemplateRex: Sure, and I referred to my IMHO correct naming convention in the reply to you. So, people can check that out in the future for proper reading. All fine, no?
  • TemplateRex
    TemplateRex almost 11 years
    @LaszloPapp I don't like sname, if I would use something other than N, i would use the more verbose but clearer name_size
  • László Papp
    László Papp almost 11 years
    @TemplateRex: that is just useless typing. Not to mention, it is also a can of worms for the camelCase vs under_score flamewar. sfoo is a pretty common practice out there, really.
  • TemplateRex
    TemplateRex almost 11 years
    @LaszloPapp And N is even less typing! For locally defined arrays that would be as concise as it gets without risking ambiguity. If more context is required, useless typing is not a relevant criterion. I like underscores myself, but in a camelCase shop, the proper name would be nameSize.
  • TemplateRex
    TemplateRex almost 11 years
    @LaszloPapp agreed on 1 and 3, but 2 has IMO readability problems for names starting with an s.
  • László Papp
    László Papp almost 11 years
    @TemplateRex: What readability problem? It is pretty common out there smyarr means the "size of myarr". Here is an example: sdata -> size of data. It is quite a common pattern out there. It is a lot more common if you take a look at google than say... data_size.