[c++] C++ String array sorting

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

This question is related to c++ arrays sorting

The answer is


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


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

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.


The multiset container uses a red-black tree to keep elements sorted.

// using the multiset container to sort a list of strings.
#include <iostream>
#include <set>
#include <string>
#include <vector>


std::vector<std::string> people = {
  "Joe",
  "Adam",
  "Mark",
  "Jesse",
  "Jess",
  "Fred",
  "Susie",
  "Jill",
  "Fred", // two freds.
  "Adam",
  "Jack",
  "Adam", // three adams.
  "Zeke",
  "Phil"};

int main(int argc, char **argv) {
  std::multiset<std::string> g(people.begin(), people.end()); // """sort"""
  std::vector<std::string> all_sorted (g.begin(), g.end());
  for (int i = 0; i < all_sorted.size(); i++) {
    std::cout << all_sorted[i] << std::endl;
  }
}

Sample Output:

Adam
Adam
Adam
Fred
Fred
Jack
Jess
Jesse
Jill
Joe
Mark
Phil
Susie
Zeke

Note the advantage is that the multiset stays sorted after insertions and deletions, great for displaying say active connections or what not.


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

My solution is slightly different to any of those above and works as I just ran it.So for interest:

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

using namespace std;

int main() {
  char *name[] = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};
  vector<string> v(name, name + 14);

  sort(v.begin(),v.end());
  for(vector<string>::const_iterator i = v.begin(); i != v.end(); ++i) cout << *i << ' ';
  return 0;
}

We can sort() function to sort string array.

Procedure :

  1. At first determine the size string array.

  2. use sort function . sort(array_name, array_name+size)

  3. Iterate through string array/


Code Snippet

#include<bits/stdc++.h>
using namespace std;

int main()
{
    ios::sync_with_stdio(false);

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

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

    sort(name, name+len);

    for(string n: name)
    {
         cout<<n<<" ";
    }
    cout<<endl;

    return 0;
}

As many here have stated, you could use std::sort to sort, but what is going to happen when you, for instance, want to sort from z-a? This code may be useful

bool cmp(string a, string b)
{
if(a.compare(b) > 0)
    return true;
else
    return false;
}

int main()
{
string words[] = {"this", "a", "test", "is"};
int length = sizeof(words) / sizeof(string);
sort(words, words + length, cmp);

for(int i = 0; i < length; i++)
    cout << words[i] << " ";
cout << endl;
    // output will be: this test is a 

}

If you want to reverse the order of sorting just modify the sign in the cmp function.

Hope this is helpful :)

Cheers!!!


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to sorting

Sort Array of object by object field in Angular 6 Sorting a list with stream.sorted() in Java How to sort dates from Oldest to Newest in Excel? how to sort pandas dataframe from one column Reverse a comparator in Java 8 Find the unique values in a column and then sort them pandas groupby sort within groups pandas groupby sort descending order Efficiently sorting a numpy array in descending order? Swift: Sort array of objects alphabetically