简体   繁体   中英

How to assign values in a range of elements inside a vector in C++?

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]++;
}

Online Demo

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; }
);

Online Demo

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; }
);

Online Demo

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM