0

I have 2 vectors that only have 4 values in each of them. I want to loop through them and process them together, as the values in both vectors go together in those positions in the vectors.

for (std::vector<boost::filesystem::path>::iterator i = volumeVec.begin(); i != volumeVec.end(); ++i) {         
        for (std::vector<boost::filesystem::path>::iterator j = sliceHeaderVec.begin(); j != sliceHeaderVec.end(); ++j) {
            ParseHeader(j->string(), i->string(), sourceDir);  
        }             
    }

However, when I run ParseHeader it process many more values then what I was expecting. I think I need to fix the arrangement of my for loops but don't know what to do

3
  • How much loop proceedings do you see, 16 or more? Commented Apr 6, 2017 at 15:12
  • 2
    your loops go through all combinations of i and j while your text sounds as if you want i going from 0 to 3 and j==i Commented Apr 6, 2017 at 15:12
  • btw to get the indices right, a much simpler example would be sufficient Commented Apr 6, 2017 at 15:13

3 Answers 3

2

You probably want something like:

assert(volumeVec.size() == sliceHeaderVec.size());
for (std::size_t i = 0; i != volumeVec.size(); ++i) {
    ParseHeader(volumeVec[i].string(), sliceHeaderVec[i].string(), sourceDir);
}

Or with range-v3:

for (const auto& p : ranges::view::zip(volumeVec, sliceHeaderVec)) {
    ParseHeader(std::get<0>(p).string(), std::get<1>(p).string(), sourceDir);
}
Sign up to request clarification or add additional context in comments.

Comments

2

If I understand you correctly you have a situation like this:

v1 = { v11, v12, v13, v14}

v2 = { v21, v22, v23, v24}

And you want a loop which process elements from both v1 and v2 in pairs {v11, v21}, {v12, v22}, {v13, v23}, {v14, v24}.

In such case you can simply use a indexed loop:

for (size_t i = 0; i < v1.size(); ++i)
{
    process(v1[i], v2[i]);
}

Before that you might want to check that v1.size() == v2.size() to avoid problems.

Comments

0

If you have two collection which you want to run an operation (aka transformation) on, my suggestion would be to use std::transform from <algorithm>. In my opinion code written with that is well readable:

Suppose you have vector<int> v1 and vector<int> v2 and want to add them, you can do:

std::transform(v1.begin(), v1.end(), v2.begin(), v1.begin(), std::plus<int>());

The last argument could also be an other iterator or a back inserter if you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.