PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, May 10, 2022

[FIXED] How to find the product of vector elements?

 May 10, 2022     algorithm, c++, c++11, product, stdvector     No comments   

Issue

I have the following vector values: [2, 3, 7].

I want to output the product of the vector, as in 2*3*7 = 42.

I wrote some code for it but it doesn't appear to be working. I am new to C++, so I am not sure how to get the product of the values in a vector given any numeric vector of any size.

#include <bits/stdc++.h>

int main()
{
    int n;
    cin >> n;
    vector<int> vec;
    while (n--) 
    {
        int temp;
        cin >> temp;
        vec.push_back(temp);
    }
    int total = 1;
    total *= vec;
    cout << vec << endl;
    return 0;
}

Solution

If you want to get the product of any numeric vector of any size, here's a function that works with any numeric type of vector with the help of templates:

template <class any>
long double vectorProduct(vector<any> vec) {
  long double total = 1;

  for(any num : vec) {
    total *= num;
  }

  return total;
}

Usage:

cout << vectorProduct(vec) << endl;


Answered By - Mystical
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing