I have a vector of ints, like {0, 0, 0, 0, 0}
. I need to increase v[i]
by 1 for a range of elements, like v[1]
to v[3]
so that I have {0, 1, 1, 1, 0}
. How to do that?
Just use a simple iterative loop, eg:
std::vector<int> v = {0, 0, 0, 0, 0};
for(size_t i = 1; i <= 3; ++i) {
v[i]++;
}
Which you can also replicate using standard library algorithms like std::for_each()
and std::transform()
, eg:
std::vector<int> v = {0, 0, 0, 0, 0};
std::for_each(v.begin()+1, v.begin()+4,
[](int& i){ ++i; }
);
std::vector<int> v = {0, 0, 0, 0, 0};
std::transform(v.begin()+1, v.begin()+4, v.begin()+1,
[](int i){ return i+1; }
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.