简体   繁体   中英

Way to distinguish objects in C++

There is a structure, that an object belongs to. There are no functions for the stucture defined. To list the objects I've used

for (auto object:objects)

But now I need to distinguish the objects to perform a different action on every 3rd object. How can I list them so I can tell which object is the 3rd?

You can use a for loop or a while loop. This way you will be able to use an index to know which object is every third one or nth one.

for(int i = 0; i < N; ++i) {
    if(i % 3 == 0)
    {   
        objects[i] // do something with this object here
    }
}

Or if it objects is not accessible by []:

int i = 0;
// remove the & if you need to use a copy of the object
for(auto& object: objects) {
    if(i % 3 == 0)
    {   
        // do something with this object here
    }
    ++i;
}

for (auto object: objects) statement means that the data structure containing objects is iterable, meaning that objects data structure has implemented begin() and end() functions. Now from what I understood you need to perform a particular action every 3 elements. The most simple ways to do it are:

  • by using an additional counter:
size_t counter = 0;
for (auto object: objects) {
    if (counter % 3 == 0) {
        // modify object
    }
    counter ++;
}

Be aware that depending on the type objects data structure when invoking for (auto object: objects) you might actually do a copy. (not passing the object by reference). This is due to the fact that auto takes the declination type of the element stored in objects data structure. To make sure you really modify the object, one needs to specify that you pass the reference: for (auto & object: objects) for instance.

  • by changing the for loop statement with iterators
for (auto it = objects.begin(); it != object.end(); it ++) {
    size_t element_position = std::distance(objects.begin(), it);
    if (element_position % 3 == 0) {
        // do something with * it which stores the object
    }
}

Be cautious that std::distance method might be linear in case that the iterator of the data structure is not a random access iterator. For more details please have a look at: https://www.cplusplus.com/reference/iterator/distance/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM