开发者

C++: How to pick out last quarter of elements in a vector?

开发者 https://www.devze.com 2023-02-21 20:13 出处:网络
What is the best way to pick out the last quarter of the elements in a vect开发者_开发问答or containg N elements?size_tn = src.size();

What is the best way to pick out the last quarter of the elements in a vect开发者_开发问答or containg N elements?


size_t   n = src.size();
std::vector<int> dest(src.begin() + (3*n)/4, src.end());

dest contains the last quarter elements from the source vector src.

You can also use std::copy from <algorithm> header file as,

std::vector<int> dest_copy;
std::copy(src.begin() + (3*n)/4, src.end(), std::back_inserter(dest_copy));

See the online demo at ideone : http://ideone.com/qrVod

I think, you may want to work more on the expression (3*n)/4. Like when n is say 5, you want to pick 1 element only, but when n is 7, you may want to pick 2 instead of 1. So this decision is upto you. My solution just tells you how would you copy the elements, once you decide exactly how many!


Something like this, I guess:

size_t lastQuarter = myVector.size() * 3 / 4;
for (size_t i = lastQuarter; i < myVector.size(); i++)
{
  doSomething(myVector.at(i));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消