Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. [SOLVED] Get all Objects with same class ?
Forum Updated to NodeBB v4.3 + New Features

[SOLVED] Get all Objects with same class ?

Scheduled Pinned Locked Moved General and Desktop
37 Posts 4 Posters 15.4k 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.
  • SGaistS Offline
    SGaistS Offline
    SGaist
    Lifetime Qt Champion
    wrote on last edited by
    #14

    As for every user of the Qt library

    STL is a different beast

    @CONFIG += c++11@

    sets everything needed to use C++11

    Interested in AI ? www.idiap.ch
    Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

    1 Reply Last reply
    0
    • D Offline
      D Offline
      deleted28
      wrote on last edited by
      #15

      I'm sorry but i need more help.
      I do not know how to work on the QSet instances.

      knhead.h:
      @#include <QObject>
      #include <QSet>

      class KNhead
      {
      public:
      KNhead();
      ~KNhead();

      QSet<KNhead*> instances;
      

      };@

      knhead.cpp:
      @#include "knhead.h"

      QSet<KNhead*> instances;

      KNhead::KNhead()
      {
      instances.insert(this);
      }

      KNhead::~KNhead()
      {
      instances.remove(this);
      }@

      main.cpp:

      @#include <QCoreApplication>
      #include <QDebug>
      #include <QSet>
      #include "knhead.h"

      int main(int argc, char *argv[])
      {
      QCoreApplication a(argc, argv);
      qDebug() << "Hello\n";

      KNhead *cell_1 = new KNhead;
      KNhead *cell_2 = new KNhead;
      KNhead *cell_3 = new KNhead;
      

      // qDebug() << ??? instances.count() ??? ;

      qDebug() << cell_1->instances.count();
      qDebug() << cell_1->instances.size();
      
      qDebug() << cell_2->instances.count();
      qDebug() << cell_2->instances.size();
      
      return a.exec(&#41;;
      

      }@

      output:
      @Hello

      1
      1
      1
      1
      @

      Is there a "static" missing ?
      or do i need ust some more coffe to wake up this morning

      1 Reply Last reply
      0
      • JKSHJ Offline
        JKSHJ Offline
        JKSH
        Moderators
        wrote on last edited by
        #16

        [quote author="wally123" date="1422779095"]Is there a "static" missing ?[/quote]Yes, your set needs to be a static variable. You want all the different KNhead instances to write to the same set, after all.

        Qt Doc Search for browsers: forum.qt.io/topic/35616/web-browser-extension-for-improved-doc-searches

        1 Reply Last reply
        0
        • D Offline
          D Offline
          deleted28
          wrote on last edited by
          #17

          just put a "static" in knhead.h line 10 and knhead.cpp line 3
          @
          static QSet<KNhead*> instances;
          @

          results in:

          error: undefined reference to `KNhead::instances'

          1 Reply Last reply
          0
          • JKSHJ Offline
            JKSHJ Offline
            JKSH
            Moderators
            wrote on last edited by
            #18

            You need to define static member variables in a .cpp file somewhere. Add this line to knhead.cpp (outside of any functions):

            @
            QSet<KNhead*> KNhead::instances;
            @

            Do some extra reading to understand "how to use static member variabless":http://www.learncpp.com/cpp-tutorial/811-static-member-variables/

            Qt Doc Search for browsers: forum.qt.io/topic/35616/web-browser-extension-for-improved-doc-searches

            1 Reply Last reply
            0
            • D Offline
              D Offline
              deleted28
              wrote on last edited by
              #19

              Ok, now no errors and it s output looks good:
              @Hello

              3
              3
              3
              3@

              Do i need always an arbitrary instance of class KNhead to access instances
              or is there another way ?

              e.g. qDebug() << cell_1->instances.count();
              or cell_2 or cell_3

              1 Reply Last reply
              0
              • G Offline
                G Offline
                gyll
                wrote on last edited by
                #20

                As i told you in my first reply (you forgot :P):
                "Once you have the above, you have access to ‘instances’ anywhere in your program (provided you #include “custom.h” in the cpp files where you use ‘instances’) via name qualification: 'Custom::instances'

                So, in any cpp file where you want to access 'instances' just make sure to #include "knhead.h" and then just use 'KNhead::instances':
                @
                #include "knhead.h"
                ...
                qDebug() << KNhead::instances.count();
                ...
                @

                1 Reply Last reply
                0
                • JKSHJ Offline
                  JKSHJ Offline
                  JKSH
                  Moderators
                  wrote on last edited by
                  #21

                  [quote author="gyll" date="1422783535"]
                  @
                  #include "knhead.h"
                  ...
                  qDebug() << KNhead::instances.count();
                  ...
                  @
                  [/quote]It's a good idea to avoid globally-accessible variables where feasible. Currently, someone can add/remove items from the set, without constructing/destroying a KNhead!

                  For more robust code, make the set private and implement a static member function that allows you to read the variable (but not modify it):

                  @
                  class KNhead
                  {
                  public:
                  static QSet<KNhead*> KNhead::instances() {
                  return m_instances;
                  }

                  private:
                  QSet<KNhead*> m_instances; // Give it a different name from the function
                  }
                  @

                  Qt Doc Search for browsers: forum.qt.io/topic/35616/web-browser-extension-for-improved-doc-searches

                  1 Reply Last reply
                  0
                  • G Offline
                    G Offline
                    gyll
                    wrote on last edited by
                    #22

                    w/r JKSH: using getters in the situations where you want to very clearly isolate the places where a data member changes is indeed considered the "clean code good practice" for ordinary data members, but if you have:

                    1. you want to provide a static getter method
                    2. you don't want to make the getter method return the actual variable because of efficiency reasons (in this particular example the getter would return a copy of the entire set each time it's called, i.e. alloc/dealloc)

                    then you'd need to make the getter return a reference to the variable, and you'd need to make the getter 'const'. but you can't have const qualifiers for static methods:

                    @
                    static QSet<KNhead*>& instances() const; // wrong: can't specify 'const' to static methods
                    @

                    Alternatively, one could provide method wrappers for all the methods that are needed in your code in conjunction with the data member (it's the cleanest way, but it takes a bit of typing and code checking), e.g. you could have a static method instanceCount(), instanceList(), etc, and use one method or another as needed in the code (sure enough, instanceList() would still return a copy of the set, but only when the full set is actually needed e.g. for iterating through it)

                    PS
                    fwiw, i personally don't bother much with write protection (not even for ordinary data members) except when writing interfaces for objects that are to be used by "the general public"; inside the nuts and bolts my own code i just let it be

                    1 Reply Last reply
                    0
                    • D Offline
                      D Offline
                      deleted28
                      wrote on last edited by
                      #23

                      @class KNhead
                      {
                      private:
                      QSet<KNhead*> m_instances;

                      public:
                      KNhead();
                      ~KNhead();

                      // static QSet<KNhead*> instances;

                      static QSet<KNhead*> instances() {
                          return m_instances;
                      }
                      
                      int testProp;
                      

                      };@

                      /knhead.h:4: error: invalid use of member 'KNhead::m_instances' in static member function
                      QSet<KNhead*> m_instances;

                      1 Reply Last reply
                      0
                      • G Offline
                        G Offline
                        gyll
                        wrote on last edited by
                        #24

                        you should have spotted the mistake yourself by now :P

                        there's a little error there, it should be:

                        private:
                        static QSet<KNhead*> m_instances;

                        i.e. the member still has to be static, just as it was until now, you only added a new static getter method but everything else remains the same (static methods can only access static data members of an object).
                        still, i have to say it again, using getters (not to mention static getters) is in my opinion an overkill when it's not a "general public" object. If i were you i'd just use the variable 'KNhead::instances' directly where i needed it.

                        1 Reply Last reply
                        0
                        • D Offline
                          D Offline
                          deleted28
                          wrote on last edited by
                          #25

                          If i understnad you correctly, you recomment to use this QSet<T*>
                          ( set of gathered objects created by gather method (?) )
                          as public and not to use JKSH's suggestion to make it private
                          and not avoid globally-accessible variables for now, because
                          to much efforts to implement it (overkill).
                          Is this correct ?

                          1 Reply Last reply
                          0
                          • SGaistS Offline
                            SGaistS Offline
                            SGaist
                            Lifetime Qt Champion
                            wrote on last edited by
                            #26

                            No, you are just missing the static qualifier in from of m_instances, JKSH's technique is fine

                            Interested in AI ? www.idiap.ch
                            Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                            1 Reply Last reply
                            0
                            • D Offline
                              D Offline
                              deleted28
                              wrote on last edited by
                              #27

                              I set the static already and it works now.
                              My above question is meant to this :

                              bq. still, i have to say it again, using getters (not to mention static getters) is in my opinion an overkill when it’s not a “general public” object. If i were you i’d just use the variable ‘KNhead::instances’ directly where i needed it.

                              1 Reply Last reply
                              0
                              • JKSHJ Offline
                                JKSHJ Offline
                                JKSH
                                Moderators
                                wrote on last edited by
                                #28

                                [quote author="wally123" date="1422790846"]If i understnad you correctly, you recomment to use this QSet<T*>
                                ( set of gathered objects created by gather method (?) )
                                as public and not to use JKSH's suggestion to make it private
                                and not avoid globally-accessible variables for now, because
                                to much efforts to implement it (overkill).
                                Is this correct ?
                                [/quote]Yes, that is what gyll recommended.

                                Both approaches work.

                                • The global approach is the "fast" way, and saves you a few lines of code at the start
                                • The the private approach is the "safe" way, and reduces the risk of you making mistakes in the future.

                                As the program designer, you need to compare the costs and benefits of the different approaches and decide which one you want.

                                I leave you with this piece of wisdom from xkcd:
                                !http://imgs.xkcd.com/comics/good_code.png(Good Code)!
                                (source: http://xkcd.com/844/ )

                                Qt Doc Search for browsers: forum.qt.io/topic/35616/web-browser-extension-for-improved-doc-searches

                                1 Reply Last reply
                                0
                                • D Offline
                                  D Offline
                                  deleted28
                                  wrote on last edited by
                                  #29

                                  nice !
                                  now the Iterator ... :)

                                  1 Reply Last reply
                                  0
                                  • D Offline
                                    D Offline
                                    deleted28
                                    wrote on last edited by
                                    #30

                                    this works to find by variable name:
                                    @
                                    QSet<KNhead*>::iterator it = qFind(KNhead::instances.begin(), KNhead::instances.end(), cell_2);@

                                    I introduced a public property to KNhead class as
                                    @int testProp;@

                                    @KNhead *cell_2 = new KNhead;
                                    cell_2->testPop = 222;
                                    @

                                    Can i find/search the object in the entire QSet by this property ?
                                    Means, find an object in KNhead::instances with testProp == 222 ?

                                    Of course i can go through each object an check each on the contents of the testProp,
                                    i want to ask if there is a direct possibility by STL or Qt .

                                    1 Reply Last reply
                                    0
                                    • JKSHJ Offline
                                      JKSHJ Offline
                                      JKSH
                                      Moderators
                                      wrote on last edited by
                                      #31

                                      If you want to search by one particular property, use a QMap instead of a QSet, and use the property as the map key.

                                      @
                                      // Declaring the map
                                      QMap<int, KNhead*> instances;
                                      @

                                      @
                                      // Inserting into the map
                                      KNhead::KNhead(int prop)
                                      {
                                      this->testProp = prop;
                                      instances[prop] = this;

                                      // ASSUMPTION: The value of this property never changes
                                      

                                      }
                                      @

                                      @
                                      // Retrieving from the map
                                      KNhead *cell = instances[222];
                                      @

                                      If you want to search by multiple properties, use an in-memory SQLite database.

                                      Qt Doc Search for browsers: forum.qt.io/topic/35616/web-browser-extension-for-improved-doc-searches

                                      1 Reply Last reply
                                      0
                                      • G Offline
                                        G Offline
                                        gyll
                                        wrote on last edited by
                                        #32

                                        just a quick correction to my last reply, dunno what was in my mind when i wrote it: i said that if declaring a static getter it should be declared as 'const', and this is not possible for static methods. however, i was wrong: in order to prevent using the getter method for changing the data value, it is the return value that should be declared as 'const', not the method itself.

                                        So it is entirely possible to declare a clean getter method which returns a const reference:

                                        @
                                        // knhead.h
                                        #include <unordered_set>

                                        class KNhead
                                        {
                                        static std::unordered_set<KNhead*> m_instances;
                                        public:
                                        KNhead();
                                        ~KNhead();
                                        static const std::unordered_set<KNhead*>& instances();
                                        };

                                        // knhead.cpp
                                        #include "knhead.h"
                                        #include <assert.h>

                                        std::unordered_set<KNhead*> KNhead::m_instances;

                                        KNhead::KNhead() {
                                        m_instances.insert(this);
                                        }

                                        KNhead::~KNhead() {
                                        assert(m_instances.count(this));
                                        m_instances.erase(this);
                                        }

                                        const std::unordered_set<KNhead*>& KNhead::instances() {
                                        return m_instances;
                                        }
                                        @

                                        With the KNhead::instances() as defined above you're safe (the compiler won't let you do something like e.g. KNhead::instances().insert(x) , it will complain about you trying to change a const reference)

                                        1 Reply Last reply
                                        0
                                        • D Offline
                                          D Offline
                                          deleted28
                                          wrote on last edited by
                                          #33

                                          great ! thanks a lot

                                          and it works !

                                          1 Reply Last reply
                                          0

                                          • Login

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved