Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's an answer using std::sort. I changed some of your C-like approach and using std::sort actually forces me to do it. The comparison function(compareStudents) needs objects so I had to create the struct. Vector has been used for the same reason although it would have been possible to keep using arrays but that's generally frowned upon.</p> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;vector&gt; using namespace std; struct Student { string name; float gpa; Student(string name, float gpa) { this-&gt;name = name; this-&gt;gpa = gpa; } }; bool compareStudents(Student a, Student b) { return a.name.compare(b.name) &lt; 0; } int main() { const int studentCount = 2; vector&lt;Student&gt; studentVector; int i; for (i = 0 ; i &lt; studentCount ; i++) { cout &lt;&lt; "Enter name " &lt;&lt; i + 1 &lt;&lt; " : "; string name; cin &gt;&gt; name; cout &lt;&lt; "Enter GPA : "; float gpa; cin &gt;&gt; gpa; cout &lt;&lt; endl; studentVector.push_back(Student(name, gpa)); } cout &lt;&lt; "\n********** Your entered data **********\n\n"; cout &lt;&lt; "\tName" &lt;&lt; "\t\t" &lt;&lt; "GPA\n\n"; vector&lt;Student&gt;::iterator it = studentVector.begin(); for (; it != studentVector.end(); ++it) { Student student = *it; cout &lt;&lt; "\t" &lt;&lt; student.name &lt;&lt; "\t\t" &lt;&lt; student.gpa; cout &lt;&lt; endl; } sort(studentVector.begin(), studentVector.end(), compareStudents); cout &lt;&lt; "\n\n******* Sorted data (w.r.t name) *******\n\n"; cout &lt;&lt; "\tName" &lt;&lt; "\t\t" &lt;&lt; "GPA\n\n"; it = studentVector.begin(); for (; it != studentVector.end(); ++it) { Student student = *it; cout &lt;&lt; "\t" &lt;&lt; student.name &lt;&lt; "\t\t" &lt;&lt; student.gpa; cout &lt;&lt; endl; } cout &lt;&lt; endl; return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload