How to Use Nested Loops with Vectors in Cpp

Can i use nested loops with vectors in cpp?

One major issue is that your getNodes function returns a copy of a vector, not the original vector. Therefore your iterators you use in the loops are not iterating over the same vector.

Instead, the iterators you're using in the nested loops are iterating over 4 different (but equivalent) vectors instead of the actual vector from the object in question.

There is nothing wrong in returning a copy of a vector in general. However when you do this, you have to make sure you call such a function if you really want a copy, and not the same vector. Using the getNodes function as you used it is not a valid usage in terms of what you are trying to accomplish.

The error is here:

inline vector<Node*> getNodes()  { return nodes; }

The fix:

inline vector<Node*>& getNodes() { return nodes; }

The latter ensures that a reference to the actual vector in question is returned, not a copy of the actual vector. You can add an additional function that returns the vector as a copy if you want to still have the functionality available.

Using iterators in nested loop through two vectors to match elements and erase from the vectors

Using standard algorithms clarifies both what you want to do and makes the control flow straightforward (unlike goto):

for (auto it1 = left_unprocessed.begin(); it1 != left_unprocessed.end(); )
{
auto eventsMatch = [&event1 = *it1](const auto& event2) {
return event1.header.stamp.nsec == event2.header.stamp.nsec;
};

auto it2 = std::find_if(right_unprocessed.begin(), right_unprocessed.end(), eventsMatch);

if (it2 != right_unprocessed.end())
{
matching_event_arrays.push_back({*it1, *it2});
it1 = left_unprocessed.erase(it1);
right_unprocessed.erase(it2);
}
else
{
++it1;
}
}

Calculation between vectors in nested for loops

I'm not sure if I understood it all correctly, but how about this?

df = data.frame("a" = c(2, 3, 3, 4), 
"b" = c(4, 4, 4, 4),
"c" = c(5, 5, 4, 4),
"d" = c(3, 4, 4, 2))

as.vector(apply(df, 1, \(x) ifelse(abs(x[1] - x[2:4]) < 2, 1, 0)))
#> [1] 0 0 1 1 0 1 1 1 1 1 1 0


Related Topics



Leave a reply



Submit