Home > Net >  Interact with every 2nd, 3rd, and 4th element of a vector until end of vecotr
Interact with every 2nd, 3rd, and 4th element of a vector until end of vecotr

Time:05-04

Let's say I have a vector of strings that each contain a 4 letter string. The exact number of strings in the vector can change depending on input but the total number of characters of all the strings will always add up to a multiple of 16 (e.g. 64 and 784). Let's say for n vectors I want to access every 2nd, 3rd, and 4th element of the vector, skipping the 1st, 5th, 9th, 13th, etc. elements in the vector. What is the best way to write a loop or function that allows me to interact and edit these strings in the vectors using C ?

CodePudding user response:

this?

     for(int i = 0; i< svec.size(); i  ){
        if(i%4!=0){
            // process string here
            noodleOn(svec[i]);
        }
     }

assuming by '1st' you mean - 'the one with index 0' etc.

CodePudding user response:

You could make a loop that increases an index by 4 every iteration. How you set the initial index value depends on what you find most easy to reason about when asked "what about if the vector happens to contain a number of strings that is not divisible by 4"?

I find this easy to reason about:

  • Start with the index at the highest index of the first 4 you are going to pick. That is 3.
  • Use the subscript operator with that index and subtract 2, 1 and 0 to pick the second, third and fourth element.
  • Finally step the index by 4.

For me this makes it clear that it'll never access the vector out of bounds:

#include <iostream>
#include <string>
#include <vector>

void interact(const std::string& x2, const std::string& x3, const std::string& x4) {
    std::cout << x2 << ',' << x3 << ',' << x4 << '\n';
}

int main() {
    std::vector<std::string> vs{"Hello", "world", "This", "is",
                                "fun",   "don't", "you",  "think"};

    for (size_t idx = 3; idx < vs.size(); idx  = 4) {
        interact(vs[idx - 2], vs[idx - 1], vs[idx - 0]);
        //            2nd          3rd          4th
    }
}

Output:

world,This,is
don't,you,think
  •  Tags:  
  • c
  • Related