std::vector<struct> insertion question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • divideby0
    New Member
    • May 2012
    • 131

    std::vector<struct> insertion question

    Is it possible to assign function parameters directly into a vector holding a structure instead of declaring a local struct variable?

    Below is sort of what I'm wanting to do; the following is declared as private data in a class

    Code:
    typedef struct
    {
        std::string s1;
        std::string s2;
        int i1;
        int i2;
    } item;
    
    std::vector<item> *items;
    I've got a member function dataAddItem()

    Code:
    bool className::dataAddItem(
       const std::string &s1,
       const std::string &s2,
       const int &i1,
       const int &i2)
    {
    
       // items->push_back(struct) ??
    }
    I'm wanting to assign the parameters without having to declare a temporary structure. Is this possible?

    TIA
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    No. Since you have a vector<item> you have to push_back and item.

    However, once the item is in the vector then you can:

    Code:
    items[n].s1 = "hello";
    This violates encapsulation but it will work.

    Don't worry about temporary copies until your code works. Then you can go through it and use references where possible. After which you replace any remaining pointers with smart poiters. However, just using references will remove 90% of your pointers.

    I am not sure why your items is a pointer vector<item>. Are you making assumptions abut how vector is implemented? I can guarantee it's not on the stack.

    Comment

    • divideby0
      New Member
      • May 2012
      • 131

      #3
      Thank you for your reply.

      I'm finding that things I'm somewhat familiar with in C go horribly wrong in C++.

      I found a bit of code that *appears* to do what I'd like but I don't know if it's valid. My knowledge of C++ is solely based on snippits of code found in forums and whatnot.

      Code:
      struct item
      {
         ...
         item(const string &p1, const string &p2, ...) :
            s1(p1), s2(p2), ... ) {}
      
      }; // handy feature but bizzare compared to C
      Code:
      bool ::dataAddItem(param list)
      {
         items->push_back(item(param list));
         // use a constructor within a struct?? weird
      }
      this compiles and runs without errors, but is it valid?

      With C, I was told it's better to use a pointer to a structure or large data, so I tried the same approach with the vector.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Please forget C. C is the reason there is a C++.

        C++ Secret: There are no classes in C++.

        In C the only way you can have a data item with members is to use a struct. Therefore, in C++ you use a struct to encapsulate members since C++ extends C.

        C++ uses constructors to initialize objects. Therefore, structs have constructors. Ditto for destructors. Member functions, etc...

        If you define every member of a struct as public, private or protected, then there is no difference between a struct and a class.

        C++ Secret #2: The "class" keyword is there to make object-oriented programmers think that C++ is object-oriented, but it's not really.

        In the OOP world a class is a pattern for an object. So you say an object is an instance of a class. The OOP world never heard of a struct since it is C language artifact. By implementing a "class" as a struct, C++ bridges C to OOP. If you can use a struct you automatically can use a class.

        Your example code just shows me a struct with a constructor.

        Comment

        • divideby0
          New Member
          • May 2012
          • 131

          #5
          Once again, I cannot thank you enough taking the time to explain things.

          Here's a compacted version of what I'm working with

          Code:
          class test
          {
             private : 
          
             struct item
             {
                 string s1;
                 string s2; 
                 item(const string &init_data1,
                      const string &init_data2) : 
                      s1(init_data1), s2(init_data2) {}
             };
          
             vector<item> items;
             vector<item>::iterator it;
          
             public : bool dataAddItem(const string &);
                      void dataShowItems();
          };
          
          bool test::dataAddItem(const string &param1,
                                 const string &param2)
          {
             items.push_back( item(param1, param2) );
          }
          
          void test::dataShowItems()
          {
              for(it = items.begin(); it != items.end(); ++it)
                 cout << it->s1
                      << "\n"
                      << it->s2
                      << "\n\n";
          }
          
          test obj;
          obj.dataAddItem("s1 data", "s2 data");
          obj.dataShowItems();
          
          // output
          // s1 data
          // s2 data
          What I don't quite get with dataAddItem is how push_back is able to use item's constructor so that "s1 data" and "s2 data" are added to the vector.

          Comment

          • weaknessforcats
            Recognized Expert Expert
            • Mar 2007
            • 9214

            #6
            Here's the line of code:

            Code:
            items.push_back( item(param1, param2) );
            So you are calling an item constructor as the argument to push_back. To make that call, the compiler creates an item object and calls the construtor on it. Now param1 and param2 are inside this hidden (temporary) item object. This temporary object is passed to push_back which adds a copy of it (copy constructor call) to the vector and finally as the temporary goes out of scope, the item destructor is called.

            In C you would need to make all these calls yourself (if you remembered) but in C++ the compiler creates, initializes and cleans up the object withut bothering you. This drives C programmers nuts since they want total control of their program. None of this automatic protection stuff.

            Comment

            • divideby0
              New Member
              • May 2012
              • 131

              #7
              Thank you; I appreciate your patience and your comments have been extremely helpful.

              Comment

              Working...