Search code examples
c++algorithmc++11cluster-analysisstdvector

How can i extract n elements out of p in a std::vector with X elements


I have a vector with X elements, how can I extract n elements (3 in the example below) out of p (6 in the example) from the vector? Here is how I did it.

//vector<int> a;
std::vector<int> a {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
                       23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35};

int X = a.size();

// code to extract 3 elements of 6 until the end of the vector
for (int i=0; i< a.size(); i+=6)
{

        if (i >= a.size())
        {
            break;
        }
        else
        {
            sub_indices.push_back(i);
        }

        if ( (i+1) >= a.size())
        {
            break;
        }
        else
        {
            sub_indices.push_back(i+1);
        }

        if ((i+2) >= a.size())
        {
            break;
        }
        else {
            sub_indices.push_back(i+2);
        }
}

Display result would output:

10 11 12 (drop three elements) 16 17 18 (drop three elements) 22 23 24  (drop three elements) 28 29 30 (drop three elements) 34 35

I did it like this but can anyone show me a more efficient way?


Solution

  • Here is the solution:

    #include <vector>
    #include <iostream>
    
    int main () {
    
      // Better to initilize the vector like this instead of using multiple push_back
      std::vector<int> a;
      for (int i=10; i<36; ++i)
        a.push_back (i);
    
      // Here is another method to initilize your vector:
    //   std::vector<int> a {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
    //                       23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35};
    
      // Here you loop over all elements and only select the three first elements
      // of every six elements:
      for (int i=0; i<a.size(); ++i) 
        if (i%6 < 3)
          std::cout << a[i] << std::endl;
    
      return 0;
    }
    

    The % operator gives the remainder of a division of two int values.