title: Sorting a Vector of struct, descending or ascending order: C++
body: <p>I am trying to sort a vector of a struct in the following code. The struct has 3 data member. and I want to load a vector from these data members and sort / order by one of the struct data members. This however does not work.
  I am using this as reference: <a href="http://www.cplusplus.com/reference/algorithm/sort/" rel="nofollow">http://www.cplusplus.com/reference/algorithm/sort/</a>
  I will appreciate any help/pointers links to go-through. Thanks.</p>
  
  <p>Sample code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  #include &lt;vector&gt;
  #include &lt;algorithm&gt;
  
  struct my_data {
      int data_id;
      string data_one;
      string data_two;
  };
  
  int main() {
      vector&lt;my_data&gt; my_vector;
      my_data new_data;
      for (int i = 0; i &lt; 3; i++) {
          if (i == 0) {
              new_data.data_id = i;
              new_data.data_one = "BBBB";
              new_data.data_two = "bbbb";
              my_vector.push_back(new_data);
          }
          if (i == 1) {
              new_data.data_id = i;
              new_data.data_one = "AAAA";
              new_data.data_two = "aaaa";
              my_vector.push_back(new_data);
          }
          if (i == 2) {
              new_data.data_id = i;
              new_data.data_one = "CCCC";
              new_data.data_two = "cccc";
              my_vector.push_back(new_data);
          }
      }
      // now, I want some help to sort my vector by "data_one",
      // something like this (below sorting function)!
      std::sort(my_vector.begin(), my_vector.end(), data_one);
      for (int i = 0; i &lt; my_vector.size(); i++) {
          cout &lt;&lt; my_vector[i].data_id
               &lt;&lt; "\t" &lt;&lt; my_vector[i].data_one
               &lt;&lt; "\t" &lt;&lt; my_vector[i].data_two &lt;&lt; endl;
      }
  }
  </code></pre>
  
  <p>I'm expecting the following output from the print out line:</p>
  
  <pre><code>cout &lt;&lt; my_vector[i].data_id &lt;&lt; "\t" &lt;&lt; my_vector[i].data_one &lt;&lt; "\t" &lt;&lt; my_vector[i].data_two &lt;&lt; endl;
  
  2      AAAA      aaaa
  1      BBBB      bbbb
  3      CCCC      cccc
  </code></pre>