vendredi 15 novembre 2019

Is there a nice way to random access another vector when using range for (C++11)?

For example, if I have two vectors, and I want to do something with each pair of elements in them respectively, I might write

// I have these two vectors
std::vector<int> a;
std::vector<int> b;

// some codes

for (int i = 0, ed = std::min(a.size(), b.size()); i < ed; ++i) {
    a[i] = func(b[i]);
}

then I read about C++11, I tried out another way:

for (auto ai = a.begin(), bi = b.begin(), aed = a.end(), bed = b.end(); ai != aed && bi != bed; ++ai, ++bi) {
    *ai = func(*bi);
}

But to say the truth this is too ugly. I tried to apply the "range for" but failed. I am a freshman but I don't want to write shitty codes so I really want to know what is the right way to do so. Can someone help teach me better means?


Oh BTW, if I want to swap two adjacent elements in a vector, how can I implement this using a range for?

Like this:

for (int i = 1; i < n; ++i)
    if (a[i] < a[i - 1])
        a[i] = a[i - 1];
for (auto & i : a)
    if (???)

Many thanks!

Aucun commentaire:

Enregistrer un commentaire