Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Sorting a vector of non-primitive data types (structs)

Sorting a vector of non-primitive data types (structs)

Scheduled Pinned Locked Moved C / C++ / MFC
tutorialgraphicsalgorithms
13 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    all_in_flames
    wrote on last edited by
    #1

    Hi everyone, I'm attempting to write a program that takes command line arguments, reads data in from a file, and then appropriately searches for certain data or sorts the data for output based on the argument passed. I am having trouble figuring out how to actually sort the vectors according to the attributes. the struct is as follows: struct Wizard { string FirstName; string LastName; int Grade; double WandWeight; }; The datafile being read from simply has each property separated by a single whitespace character. The vector is declared simply as: vector(Wizard) wizVec; (NOTE: angle braces would not show up in preview, assume they take the place of the round braces in the vector declaration) Don't ask about the name of the struct, it's my prof's example! Any suggestions or solutions are appreciated and needed! Thanks in advance!

    C S A 3 Replies Last reply
    0
    • A all_in_flames

      Hi everyone, I'm attempting to write a program that takes command line arguments, reads data in from a file, and then appropriately searches for certain data or sorts the data for output based on the argument passed. I am having trouble figuring out how to actually sort the vectors according to the attributes. the struct is as follows: struct Wizard { string FirstName; string LastName; int Grade; double WandWeight; }; The datafile being read from simply has each property separated by a single whitespace character. The vector is declared simply as: vector(Wizard) wizVec; (NOTE: angle braces would not show up in preview, assume they take the place of the round braces in the vector declaration) Don't ask about the name of the struct, it's my prof's example! Any suggestions or solutions are appreciated and needed! Thanks in advance!

      C Offline
      C Offline
      Christian Graus
      wrote on last edited by
      #2

      To get < and > to show, you need to check 'Ignore HTML tags' below. You can write a function object that compares two Wizard objects, and pass that into the sort algorithm. Here[^] is an article on the subject.

      Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

      1 Reply Last reply
      0
      • A all_in_flames

        Hi everyone, I'm attempting to write a program that takes command line arguments, reads data in from a file, and then appropriately searches for certain data or sorts the data for output based on the argument passed. I am having trouble figuring out how to actually sort the vectors according to the attributes. the struct is as follows: struct Wizard { string FirstName; string LastName; int Grade; double WandWeight; }; The datafile being read from simply has each property separated by a single whitespace character. The vector is declared simply as: vector(Wizard) wizVec; (NOTE: angle braces would not show up in preview, assume they take the place of the round braces in the vector declaration) Don't ask about the name of the struct, it's my prof's example! Any suggestions or solutions are appreciated and needed! Thanks in advance!

        S Offline
        S Offline
        Stephen Hewitt
        wrote on last edited by
        #3

        Use std::sort to sort the vector. Add an operator < for your struct to define the sort order or code a predicate function or functor and pass it to std::sort.

        Steve

        A 1 Reply Last reply
        0
        • S Stephen Hewitt

          Use std::sort to sort the vector. Add an operator < for your struct to define the sort order or code a predicate function or functor and pass it to std::sort.

          Steve

          A Offline
          A Offline
          all_in_flames
          wrote on last edited by
          #4

          Thanks for the article Christian, and the suggestion, Stephen. I will try to follow the instructions in the article. I appreciate the help, and the speedy replies :) Does this logic make sense in context? void SortVecAscending(vector &wizVector, string prop) { // Sort vector smallest to largest, according to prop(erty) bool compare_Wizards(const Wizard& a, const Wizard& b) { return a.prop < b.prop; } std::sort(wizVector.begin(), wizVector.end(), compare_Wizards); }

          C S 2 Replies Last reply
          0
          • A all_in_flames

            Thanks for the article Christian, and the suggestion, Stephen. I will try to follow the instructions in the article. I appreciate the help, and the speedy replies :) Does this logic make sense in context? void SortVecAscending(vector &wizVector, string prop) { // Sort vector smallest to largest, according to prop(erty) bool compare_Wizards(const Wizard& a, const Wizard& b) { return a.prop < b.prop; } std::sort(wizVector.begin(), wizVector.end(), compare_Wizards); }

            C Offline
            C Offline
            Christian Graus
            wrote on last edited by
            #5

            Yes, that looks like it should work.

            Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

            S 1 Reply Last reply
            0
            • A all_in_flames

              Hi everyone, I'm attempting to write a program that takes command line arguments, reads data in from a file, and then appropriately searches for certain data or sorts the data for output based on the argument passed. I am having trouble figuring out how to actually sort the vectors according to the attributes. the struct is as follows: struct Wizard { string FirstName; string LastName; int Grade; double WandWeight; }; The datafile being read from simply has each property separated by a single whitespace character. The vector is declared simply as: vector(Wizard) wizVec; (NOTE: angle braces would not show up in preview, assume they take the place of the round braces in the vector declaration) Don't ask about the name of the struct, it's my prof's example! Any suggestions or solutions are appreciated and needed! Thanks in advance!

              A Offline
              A Offline
              all_in_flames
              wrote on last edited by
              #6

              Thanks again for all your help, gentlemen. I got the sorting working with no more problems. However, now that I have moved on to the searching portion, I find that the way the project is designed, I have to search for values in the structs that are NOT strings. To refresh your memory: struct Wizard { string FirstName; string LastName; int Grade; double WandWeight; }; Is there any viable way to convert a string to an int, a string to a double, or vice versa? I have attempted to use static_cast() on the int and double values, and static_cast() / static_cast() on the string values, but the compiler didn't like those conversions. I have looked around, and there is nothing available to me without downloading someone's class and using it. Since this is a school project, I have a feeling that would be frowned upon. Any ideas? If any clarification is needed, simply ask.

              S M 2 Replies Last reply
              0
              • C Christian Graus

                Yes, that looks like it should work.

                Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

                S Offline
                S Offline
                Stephen Hewitt
                wrote on last edited by
                #7

                C++ does not support local functions (functions in functions). You can have functors in function however.

                Steve

                1 Reply Last reply
                0
                • A all_in_flames

                  Thanks for the article Christian, and the suggestion, Stephen. I will try to follow the instructions in the article. I appreciate the help, and the speedy replies :) Does this logic make sense in context? void SortVecAscending(vector &wizVector, string prop) { // Sort vector smallest to largest, according to prop(erty) bool compare_Wizards(const Wizard& a, const Wizard& b) { return a.prop < b.prop; } std::sort(wizVector.begin(), wizVector.end(), compare_Wizards); }

                  S Offline
                  S Offline
                  Stephen Hewitt
                  wrote on last edited by
                  #8

                  C++ does not support local functions (functions in functions). You can have functors in function however.

                  Steve

                  1 Reply Last reply
                  0
                  • A all_in_flames

                    Thanks again for all your help, gentlemen. I got the sorting working with no more problems. However, now that I have moved on to the searching portion, I find that the way the project is designed, I have to search for values in the structs that are NOT strings. To refresh your memory: struct Wizard { string FirstName; string LastName; int Grade; double WandWeight; }; Is there any viable way to convert a string to an int, a string to a double, or vice versa? I have attempted to use static_cast() on the int and double values, and static_cast() / static_cast() on the string values, but the compiler didn't like those conversions. I have looked around, and there is nothing available to me without downloading someone's class and using it. Since this is a school project, I have a feeling that would be frowned upon. Any ideas? If any clarification is needed, simply ask.

                    S Offline
                    S Offline
                    Stephen Hewitt
                    wrote on last edited by
                    #9

                    There are multiple ways, here's one:

                    // CommandLine.cpp : Defines the entry point for the console application.
                    //
                     
                    #include "StdAfx.h"
                    #include <iostream>
                    #include <string>
                    #include <sstream> // For 'istringstream'.
                     
                    int main()
                    {
                    using namespace std;
                     
                    string s = "1234";
                    int num;
                    istringstream ss(s);
                    ss >> num;
                    if (ss)
                    {
                    cout << "Number is " << num << endl;
                    }
                     
                    return 0;
                    }

                    And another:

                    // CommandLine.cpp : Defines the entry point for the console application.
                    //
                     
                    #include "StdAfx.h"
                    #include <iostream>
                    #include <string>
                    #include <cstdlib>
                     
                    int main()
                    {
                    using namespace std;
                     
                    string s = "1234";
                    int num = atoi(s.c_str());
                    cout << "Number is " << num << endl;
                     
                    return 0;
                    }

                    The second method is easier but error handling is more difficult as if no valid conversion could be performed, a zero value is returned. Also, in the first version simply changing the type of the num variable will make the code work different types but the second version requires a distinct function for each type: atoi only works for ints.

                    Steve

                    A 1 Reply Last reply
                    0
                    • S Stephen Hewitt

                      There are multiple ways, here's one:

                      // CommandLine.cpp : Defines the entry point for the console application.
                      //
                       
                      #include "StdAfx.h"
                      #include <iostream>
                      #include <string>
                      #include <sstream> // For 'istringstream'.
                       
                      int main()
                      {
                      using namespace std;
                       
                      string s = "1234";
                      int num;
                      istringstream ss(s);
                      ss >> num;
                      if (ss)
                      {
                      cout << "Number is " << num << endl;
                      }
                       
                      return 0;
                      }

                      And another:

                      // CommandLine.cpp : Defines the entry point for the console application.
                      //
                       
                      #include "StdAfx.h"
                      #include <iostream>
                      #include <string>
                      #include <cstdlib>
                       
                      int main()
                      {
                      using namespace std;
                       
                      string s = "1234";
                      int num = atoi(s.c_str());
                      cout << "Number is " << num << endl;
                       
                      return 0;
                      }

                      The second method is easier but error handling is more difficult as if no valid conversion could be performed, a zero value is returned. Also, in the first version simply changing the type of the num variable will make the code work different types but the second version requires a distinct function for each type: atoi only works for ints.

                      Steve

                      A Offline
                      A Offline
                      all_in_flames
                      wrote on last edited by
                      #10

                      Thanks again! I ended up using the stringstream approach, as our prof is fanatical about us not using "pure" C functions. You guys are life savers! Regards, Bryan

                      S 1 Reply Last reply
                      0
                      • A all_in_flames

                        Thanks again! I ended up using the stringstream approach, as our prof is fanatical about us not using "pure" C functions. You guys are life savers! Regards, Bryan

                        S Offline
                        S Offline
                        Stephen Hewitt
                        wrote on last edited by
                        #11

                        Your professor is a wise man.

                        Steve

                        1 Reply Last reply
                        0
                        • A all_in_flames

                          Thanks again for all your help, gentlemen. I got the sorting working with no more problems. However, now that I have moved on to the searching portion, I find that the way the project is designed, I have to search for values in the structs that are NOT strings. To refresh your memory: struct Wizard { string FirstName; string LastName; int Grade; double WandWeight; }; Is there any viable way to convert a string to an int, a string to a double, or vice versa? I have attempted to use static_cast() on the int and double values, and static_cast() / static_cast() on the string values, but the compiler didn't like those conversions. I have looked around, and there is nothing available to me without downloading someone's class and using it. Since this is a school project, I have a feeling that would be frowned upon. Any ideas? If any clarification is needed, simply ask.

                          M Offline
                          M Offline
                          Michael Dunn
                          wrote on last edited by
                          #12

                          all_in_flames wrote:

                          Is there any viable way to convert a string to an int, a string to a double, or vice versa?

                          For future reference, we have a FAQ here :) -- 6.3 How can I change a number into its string representation, or vice versa? [^]

                          --Mike-- Visual C++ MVP :cool: LINKS~! Ericahist | PimpFish | CP SearchBar v3.0 | C++ Forum FAQ Ford, what's this fish doing in my ear?

                          A 1 Reply Last reply
                          0
                          • M Michael Dunn

                            all_in_flames wrote:

                            Is there any viable way to convert a string to an int, a string to a double, or vice versa?

                            For future reference, we have a FAQ here :) -- 6.3 How can I change a number into its string representation, or vice versa? [^]

                            --Mike-- Visual C++ MVP :cool: LINKS~! Ericahist | PimpFish | CP SearchBar v3.0 | C++ Forum FAQ Ford, what's this fish doing in my ear?

                            A Offline
                            A Offline
                            all_in_flames
                            wrote on last edited by
                            #13

                            Thanks for the info, Mike! I'm a codeproject n00b, but I get the newsletter! ;)

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups