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

后端 未结 4 1933
孤城傲影
孤城傲影 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:40

    As far as I know the only way is to iterate through the vector, and apply the multiplication.

    You could define a function like so:

    void VecMultiply(std::vector& pVector, int Multiplier);
    

    and implement it like:

    void VecMultiply(std::vector& pVector, int Multiplier)
    {
        for (unsigned int i = 0; i < pVector.size(); i++)
        {
            *pVector[i] *= Multiplier;
        }
    }
    

    Or you could even pass a vector of anything multiplied by anything using templates:

    template
    template
    void VecMultiply(std::vector& pVector, M Multiplier)
        {
            for (unsigned int i = 0; i < pVector.size(); i++)
            {
                *pVector[i] *= Multiplier;
            }
        }
    

提交回复
热议问题