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;
a.push_back(10); a.push_back(11); a.push_back(12); a.push_back(13); a.push_back(14); a.push_back(15); a.push_back(16); a.push_back(17);
a.push_back(18); a.push_back(19); a.push_back(20); a.push_back(21); a.push_back(22); a.push_back(23); a.push_back(24); a.push_back(25);
a.push_back(26); a.push_back(27); a.push_back(28); a.push_back(29); a.push_back(30); a.push_back(31); a.push_back(32); a.push_back(33);
a.push_back(34); a.push_back(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)
{
int j = i+10;
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 tell me if there is a more efficient way?
Aucun commentaire:
Enregistrer un commentaire