C++ STL alternative to nested loops in a vector

170 Views Asked by At

As Sean Parent once required I'd like to eliminate raw loops in some code using C++20. Does it makes sense? If so, how?

In my example it's a vector of objects I need to merge under some conditions. So there seem to be two sub tasks for me.

The first is how could I replace nested loops by using STL algorithms. This is the kind a nested loops I write about:

for (size_t i = vector1.size() - 1; i > 0; --i)
{
    for (size_t j = 0; j < i; ++j)
    {
           if (isMergable(vector1[i], vector1[j]))
           {
                    merge(vector1[i], vector1[j])
           }
    }
}

The second is how to do it when the content of the vector changes while looping. As mentioned I'd like to merge two objects under particular conditions, which means the destination object absorbs some properties of the source object and the source object vanishes.

I guess when consider this sub tasks separately the result after the second sub task will not be the same as when look at this as one task. I haven't found a fitting STL algorithm, even to replace that nested loops.

I'm glad to recieve any help I can learn from.

Thanks.

EDIT
An object could be like that:

struct myObject {
    int number;
    std::string word;
};

This object may have a number value or a word value. A merge of two objects is possible when both have filled the number or both have filled the word. A merge would mean to sum up the numbers or to concatenate the words. The vector would consists of an amount of objects, some with a number, some with a word. After merging the vector consists only of two objects: one with sumed up numbers, the other with concatenated words.

0

There are 0 best solutions below