data structure question

This is a discussion on data structure question within the C++ Programming forums, part of the General Programming Boards category; I am new to C++ (this will become obvious) and wanted to know how I can pass data from one ...

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    6

    data structure question

    I am new to C++ (this will become obvious) and wanted to know how I can pass data from one container to another container both of which are located in different classes? I don't have any code to show otherwise I would post it. I would appreciate a good example. Thank you!
    Victor
    Last edited by miami_victor; 12-30-2004 at 01:45 PM.

  2. #2
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,088
    This question sounds very familiar.

    There a literally hundreds of variations on how this could be done. More information should be provided before a useful answer can be given. What kind of container? How are these containers accessible within their respective classes? What type(s) of object(s) do they hold?

    Regardless, here is an example that will probably be of no use to you:
    Code:
    #include <set>
    
    class A
    {
    public:
        // ...
        std::set<int> data;
    };
    
    class B
    {
    public:
        // ...
        std::set<int> data;
    };
    
    int main()
    {
        A a;
        B b;
        // ...
        b.data = a.data;  // <-- data passed here
    }

  3. #3
    Registered User
    Join Date
    Dec 2004
    Posts
    6
    Your example is very clear to me. Both containers hold the same types of data...I don't know if that helps at all. What do you mean by "what kind of container" and "How are these containers accessible within their respective classes"?

  4. #4
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,088
    > "what kind of container"
    There are many different types of containers in C++. There are STL containers like vector, set, map, multimap, multiset, deque, list and string. There are arrays, user-defined linked lists, binary trees, b-trees, hash tables, etc. All of these can be considered containers, but how you pass data from one to another is potentially different for each type.

    > "How are these containers accessible within their respective classes"
    Are the containers public members like in my example? Are they private members with public accessor functions (like they should be)? What are the available accessor functions? In other words, how can you access the data in the container if you have an instance of the class?

  5. #5
    Registered User
    Join Date
    Dec 2004
    Posts
    6
    Oh good...both containers are public. One is "map" the other "vector".

  6. #6
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,088
    Quote Originally Posted by miami_victor
    Both containers hold the same types of data.
    If one is a map, and one is a vector, it is unlikely that they contain the same types of data. A map contains a pair object, so unless your vector also contains a pair object, the data types are different.

    How are the map and vector declared? For example, std::map<int, std::string> and std::vector<std::string>.

  7. #7
    Registered User
    Join Date
    Dec 2004
    Posts
    6
    Here are my two containers. I have added comments within each...an attempt to show definitions of some of the data structures contained in each container. I hope this doesn't muddy the original question of passing data from this first container to the second container...both of which are depicted below.



    Code:
        
    struct Message_t
        {
            // Type of message received
            MsgType_t type;
    
            // Callsign of train that sent the message
            std::string trainId;
    
            std::string traintext;
    
            // the following is only here to illustrate the definition of
            // "coord_struct"  which is in "Train_Coord_struct" below.
    	//typedef struct{
    	//	int type;
    	//	int id;
    	//	float latitude;
    	//	float longitude;
    	//} coord_struct;
    
    
    	// the following message data is only here to illustrate the "Train_Coord_struct" data below.
    	//struct Train_Coord_struct{
    		//int		Packet_Type;
            	//int		sending_station;
    		//char	        sending_Id[10];
    		//int		rcv_station;
    		// bitfield for each station 0-7
    		//int     num_coord;
    		//coord_struct	coord[10];
    	//};
    
            Train_Coord_struct        Train_Location_Data;
    
        };
    
        // Container type for  messages received.
        typedef std::vector<Message_t> MessageCont_t;
    
    
    Data goes TO: 
    
        /// Attributes for a train. 
        struct Train_t
        {
            // Unique number for the train. Valid values are 1 to MAX_TRAINS.
            unsigned number;
    
            // Type of train, eg. cargo, passenger, etc.
            TrainType_t type;
    
            // Id identifies the train as a certain symbol representing the
            // kind of train.
            TrainId_t id;
    
            // Any 3 characters that an engineer of a train wishes to enter for the his/her train.
            std::string TrainText;
    
            // Estimated time to Enroute
            SP::Time_t ETE;
    
            // Estimated Time of Arrival
            SP::Time_t ETA;
    
            // Range from the train to the station.
            float range_km;
    
            // Bearing from the train to the station.
            float bearing_deg;
    
                    // The following is only here to illustrate the content of "TrainPosition_t" below.
    	//struct TrainPosition_t
        	//{
    
    	       //  float latitude;
    	       //  float latMin;
                   //  float longitude;
                   //  float longMin;
                   //  float x_meters;
                   //  float y_meters;
    
            // Position of the train.
            SP::TrainPosition_t position;
    };
    
    
        /// Container of trains
        typedef std::map<int, Train_t> TrainCont_t;
    Last edited by miami_victor; 12-30-2004 at 03:11 PM.

  8. #8
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,088
    The next question is how, in general, does data from a Message_t object get put into a Train_t object. Since they do not have the same types, you must get the data you want out of the Message_t and put into the Train_t. I'm not sure if there is a direct correlation between a Message_t and a Train_t, so you will have to give or figure out more information on how they relate to each other.

    In addition, what is the int that is the key for the TrainCont_t map supposed to represent? Is that supposed to come from the Message_t data, or is it an ID of some sort that is separate?


    Once you know how to take data from a Message_t and put it into one or more Train_t objects, you can write a function that goes through each object in the MessageCont_t vector and adds the approriate corresponding data to the TrainCont_t map.

  9. #9
    Registered User
    Join Date
    Dec 2004
    Posts
    6
    Can you show an example of how some of the objects in the MessageCont_t vector can be passed to the approriate corresponding data to the TrainCont_t map?

  10. #10
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,088
    No, because I don't know how Message_t relates to Train_t.

    Here is an example of how you can transfer data from a vector to a map, but it really depends on how the two different types relate to each other.
    Code:
    #include <vector>
    #include <map>
    #include <string>
    
    struct data1
    {
        data1() : d() { }
        double d;
        std::string s;
    };
    
    struct data2
    {
        std::string s;
    };
    
    int main()
    {
        std::vector<data1> myVec(10);
        std::map<int, data2> myMap;
    
        int ID = 0;
        std::vector<data1>::const_iterator curData1 = myVec.begin();
        std::vector<data1>::const_iterator endData1 = myVec.end();
        for(; curData1 != endData1; ++curData1)
        {
            data2 newData;
            newData.s = curData1->s;
            myMap.insert(std::make_pair(ID++, newData));
        }
    }

  11. #11
    Registered User
    Join Date
    Dec 2004
    Posts
    6
    What does "myMap.insert(std::make_pair(ID++, newData));" do? ...and thanks for all your help!

  12. #12
    Registered User
    Join Date
    Dec 2004
    Posts
    95
    Maps store pairs of values (type std:air). The pair has two data members (!), one of the first template type for the map, the other of the second. make_pair is a little utility function provided by the standard library to make an std:air from two values.

    The important thing about maps is that they're associative containers - you use the first pair member as a lookup key for the second. Say you wanted to find people by name:

    struct person_info{
    int phone;
    string address;
    //bla
    };

    map<string, person_info> PeopleFinder;

    person_info bob_info;
    bob_info.phone = 39409340;

    string Bob = "Bob";

    PeopleFinder.insert(std::make_pair(Bob, bob_info));

    Now you can look up Bob's info by supplying his name:

    map<string,person_info>::iterator i = PeopleFinder.find (Bob);

  13. #13
    RoD
    RoD is offline
    Redundantly Redundant RoD's Avatar
    Join Date
    Sep 2002
    Location
    Missouri
    Posts
    6,331
    >What does "myMap.insert(std::make_pair(ID++, newData));" do?
    Make a pair out of ID and newData and insert that pair into myMap. Then increment ID by one.

  14. #14
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,670
    >>
    >> how I can pass data from one container to another container >> both of which are located in different classes?
    >>

    from the standpoint of container design, generalizing the process of iteration is the key to flexible data transfer. consider the two STL objects vector and list - neither has any 'knowledge' of the existance of or mechanisms governing the other, yet they interoperate rather easily:

    Code:
    void print(int value) {
     cout << value << endl;
     }
     
    int main() {
     vector <int> svect;
     list <int> slist;
     for(int i = 0; i < 10; ++i) {
      svect.push_back(i);
      }
     slist.assign(svect.begin(), svect.end());
     for_each(slist.begin(), slist.end(), print); 
     return 0;
     }
    when the actual objects *themselves* differ, there are several ways you can get them to cooperate with one another. one way is to overload specific member functions to expect the other in assignment (also referred to as 'tight-coupling'):

    Code:
    struct bar;
     
    struct foo {
     foo(int set);
     foo(const foo & rhs); 
     foo(const bar & bar); 
     int value;
     };
     
    struct bar {
     bar(int set);
     bar(const bar & rhs);
     bar(const foo & foo); 
     int value;
     };
    
     foo::foo(int set) 
     : value(set) {
      
      }
     foo::foo(const foo & rhs) 
     : value(rhs.value) {
      
      }
     foo::foo(const bar & bar) 
     : value(bar.value) {
      
      } 
     
     bar::bar(int set) 
     : value(set) {
      
      }
     bar::bar(const bar & rhs) 
     : value(rhs.value) {
      
      }
     bar::bar(const foo & foo) 
     : value(foo.value) {
      
      } 
     
    void printfoo(foo & foo) {
     cout << foo.value << endl;
     }
     
    int main() {
     vector <bar> bvect;
     list <foo> flist;
     for(int i = 0; i < 10; ++i) {
      bvect.push_back(i);
      }
     flist.assign(bvect.begin(), bvect.end());
     for_each(flist.begin(), flist.end(), printfoo); 
     return 0;
     }
    another way to do it and have it work with many types of objects is to use member function templates - as long as each object conforms to a specific 'contract' (the syntax for extracting the data), they will interoperate properly:

    Code:
    struct foo {
      template <class T> 
     foo(const T & object)
     : value((int)object) {
      
      } 
      template <class T> 
     foo & operator = (const T & object) {
      value = (int)object;
      return *this;
      }   
     operator int (void) const { /* the contract */
      return value;
      } 
     int value;
     };
     
    struct bar {
      template <class T> 
     bar(const T & object)
     : value((int)object) {
      
      } 
      template <class T> 
     bar & operator = (const T & object) {
      value = (int)object;
      return *this;
      }   
     operator int (void) const { /* the contract */
      return value;
      } 
     int value;
     };
    
    void print(int value) {
     cout << value << endl;
     }
     
    int main() {
     vector <bar> bvect;
     list <foo> flist;
     for(int i = 0; i < 10; ++i) {
      bvect.push_back(i);
      }
     flist.assign(bvect.begin(), bvect.end());
     for_each(flist.begin(), flist.end(), print); 
     return 0;
     }
    using the above example, *any* object that can be casted to an int can be used by foo and bar as a data source - their interfaces are completely decoupled from external objects. this mechanism is very similar to how STL containers interact with eachother actually (ie: generic contracts). the STL is a great source for generic programming techniques, by the way. I'd suggest you get a good reference book on it and study the header files, too.



    ITSA
    Socket Library!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data structure for french-english dictionary
    By officedog in forum C Programming
    Replies: 9
    Last Post: 03-20-2009, 01:43 AM
  2. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 08:35 AM
  3. question regarding outputting data to adobe flash
    By hoax464 in forum C++ Programming
    Replies: 1
    Last Post: 07-21-2008, 01:08 PM
  4. advice on a data structure
    By ventolin in forum C++ Programming
    Replies: 7
    Last Post: 03-23-2004, 09:34 PM
  5. Help require for some data structure topics
    By jawwadalam in forum A Brief History of Cprogramming.com
    Replies: 10
    Last Post: 12-15-2002, 06:09 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21