Pergunta

Having this vector

vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

how can I compute the sum of the first half of it (which is 15) using the accumulate function?

Can I do this using the for loop with only the iterators (not numerical indexes)?

Foi útil?

Solução

You can

accumulate(v.begin(), v.begin()+int(v.size()/2), 0)

if v is your vector.

You can also write a loop:

int sum = 0;
for (vector<int>::iterator it = v.begin(); it != v.begin+int(v.size()/2); ++it) {
    sum += *it;
}

Outras dicas

To work with just the first half you have to get iterators that cover just that range. Usually people want to work with an entire container and so they use begin and end functions, but that's not the only way:

auto begin = std::begin(v);
auto middle = std::begin(v) + v.size()/2; // works for random access iterators

auto middle = begin;
std::advance(middle, v.size()/2);

advance works for input iterators or better, but for input iterators which are not also one of the other types the items that are advanced passed won't be accessible anymore.

auto middle = std::next(begin, v.size()/2); // C++11. works for forward iterators

And these are only a few of the available operations you can perform on the different types of iterators.


So now that you can create iterators that specify your desired range you can use them either in std::accumulate or a manual for loop:

std::accumulate(std::begin(v), std::next(std::begin(v), v.size()/2), 0);

for (auto begin(std::begin(v)), end(begin+v.size()/2); begin!=end; ++begin) {
    ...
}
accumulate<int>(v.cbegin(), v.cbegin() + v.size()/2, 0);

int sum = std::accumulate(v.begin(), v.begin() + v.size() / 2, 0);

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top