How do I efficiently multiply a range of values of an array with a given number?

后端 未结 4 1927
孤城傲影
孤城傲影 2021-02-06 18:49

The naive way would be to linearly iterate the range and multiply with each number in the range.

Example: Array: {1,2,3,4,5,6,7,8,9,10}; Multiply index 3 to index 8 wit

4条回答
  •  温柔的废话
    2021-02-06 19:53

    You can follow a linear approach and code it in C++11 like

    std::array nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    std::for_each(nums.begin() + 2, nums.begin() + 8, [](int & n) { n *= 2; });
    for (int & n : nums) std::cout << n << " ";
    

    Output

    1 2 6 8 10 12 14 16 9 10 
    

提交回复
热议问题