This question already has answers here:
C++ Multiplying elements in a vector
(3 answers)
Closed 3 years ago.
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;
}
Using std::accumulate, one can do
#include <numeric> // std::accumulate
#include <functional> // std::multiplies
const auto total = std::accumulate(vec.cbegin(), vec.cend(), 1, std::multiplies<int>{});
By wrapping into a templated function, the code would be more generic
template<typename Type>
auto product(const std::vector<Type>& vec, Type init)
{
return std::accumulate(vec.cbegin(), vec.cend(), init, std::multiplies<Type>{});
}
and call it with
const auto total = product(vec, /*value to be initialized/ started with*/);
With std, you might use std::accumulate:
int product(const std::vector<int>& v)
{
return std::accumulate(v.begin(), v.end(), 1, std::multiplies<>{});
}
Try multiplying each value inside the vector.
for(std::size_t i=0; i<vec.size(); i++) {
total *= vec[i];
}
Here is what I would do for your example:
#include <iostream>
int main ()
{
int n;
std::cin >> n;
int total = 1;
while(n--) {
int temp;
std::cin >> temp;
total *= temp;
}
std::cout << "Total: " << total << std::endl;
return 0;
}
My solution uses std::accumulate with the operator std::multiplies to accumulate all elements by multiplying them. By just modifying your code, the end result would be:
#include <bits/stdc++.h>
int main() {
int n;
std::cin >> n;
std::vector<int> vec;
while(n--) {
int temp;
std::cin >> temp;
vec.push_back(temp);
}
int result = std::accumulate(std::begin(vec), std::end(vec), 1, std::multiplies<int>());
std::cout << result << std::endl;
return 0;
}
You were not processing the vector at all, and also outputting the vector but not the total result.
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;
Related
I am trying to create a 2-D vector that as column 0 it would have integers and column 1 would have vectors.
For example:
column[0] column[1]
2 {2}
5 {1,2,0}
12 {4,7,9,0,0,1,6,0,0}
3 {6}
column 0 would be user input while column 1 I will calculate it on my own - I don't mind if it has dummy vectors for now and after the user exits then it would print the 2-D vector.
What I tried is:
int main() {
unsigned int input;
vector<vector<unsigned int>> v;
while (cin >> input) // enter non int to exit
for(int i=0; i<input;i++){
vector<int> factorial; //calc in a separate function - dummy vector for now
for (int j=0; j<factorial.size(); j++){
v[i].push_back(input); //set column 0 as input
v[i][j].push_back(factorial); //set column 1 as the vector containing the factorial of input
}
}
return 0;
}
Seems like you need to use class:
#include <iostream>
#include <vector>
using namespace std;
template<class T1, class T2>
class Columns{
public:
vector<T1> input;
vector<T2> output;
};
int main(){
Columns<int, int> columns; //Or, if you need to have vector in "output": \
Columns<int, vector<int>> columns;
//Usage:
columns.input.push_back(2);
columns.output.push_back(2);
return 0;
}
But, if you need more shortest implementations, you can use map:
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main(){
map<int, vector<int>> result;
for(int i = 0; i < 10; i++)
result[i] = factorial(i); //Where factorial() is function that returns vector
for(auto res: result){
cout << "Input: " << res.first << "; Result: {";
for(auto res2: res.second)
cout << res2 << "; ";
cout << "};" << endl;
}
}
So in "map" case, output should be like this:
Input: 0; Result: {Numbers here};
...
Input: 9; Result: {Numbers here};
Otherwise, you can just use 2 different arrays or vectors:
Maybe, it's the best option for you now.
#include <iostream>
#include <vector>
using namespace std;
template<class T>
vector<T> FactorialNumbers(T input){
vector<T> result;
for((input < 0) ? return result : input = input; input != 0; input--)
result.push_back(input);
return result;
}
int main() {
vector<int> input;
vector<vector<int>> output;
int usrInput = 0;
while(cin >> usrInput){
input.push_back(usrInput);
output.push_back(FactorialNumbers(usrInput));
}
}
And if you work with int only, you can change FactorialNumbers like this:
int FactorialNumbers(int input){
vector<int> result;
for((input < 0) ? return result : input = input; input != 0; input--)
result.push_back(input);
return result;
}
You can also try: vector<pair<int, std::vector<int>>>
I am new to C++, and I have run into a total lack of understanding on how to sum only even values stored in a vector in C++.
The task itself requests a user to input some amount of random integers, stop when input is 0, and then to return the amount of even values and the sum of those even values.
This is as far as I have managed to get:
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main()
{
vector<int> vet;
int s = 1;
while (s != 0) {
std::cin >> s;
vet.push_back(s);
}
int n = count_if(vet.begin(), vet.end(),
[](int n) { return (n % 2) == 0; });
cout << n << endl;
//here is the start of my problems and lack of undertanding. Basically bad improv from previous method
int m = accumulate(vet.begin(), vet.end(), 0,
[](int m) { for (auto m : vet) {
return (m % 2) == 0; });
cout << m << endl; //would love to see the sum of even values here
return 0;
}
The function to be passed to std::accumulate takes 2 values: current accumulation value and value of current element.
What you should do is add the value if it is even and make no change when not.
int m = accumulate(vet.begin(), vet.end(), 0,
[](int cur, int m) {
if ((m % 2) == 0) {
return cur + m; // add this element
} else {
return cur; // make no change
}
});
From c++20, you can separate out the logic that checks for even numbers, and the logic for summing up those values:
auto is_even = [](int i) { return i % 2 == 0; };
auto evens = vet | std::views::filter(is_even);
auto sum = std::accumulate(std::begin(evens), std::end(evens), 0);
Here's a demo.
This is my solution(sorry if it's not right I'm writing it on my phone)
You don't need a vector form this, you just need to check right from the input if the number is divisible to 2
My solution:(a littie bit ugly)
#include <iostream>
using namespace std;
int main()
{
int s {1};
int sum{};
int countNum{};
while (s != 0)
{
cin >> s;
if (s % 2 == 0)
{
sum += s;
countNum++;
}
}
cout << countNum << ' ' << sum;
}
i don't realy know what you want to do in the second part of your code but you can sum the even numbers by this way and i want to told you another thing when you using namespace std you don't need to write std::cin you can only write cin directly
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vet;
int s = 1;
//Take Input
while (s != 0) {
cin >> s;
vet.push_back(s);
}
//count elements
int elements_count = vet.size(); //vet.size() return the total number of elements of vector
//store the sum here
int sum=0;
//loop on the vector and sum only even numbers
for(int i=0;i<elements_count;i++){
if(vet[i] %2 ==0)
sum += vet[i];//check of the element of index i in the vector is even if it true it will add to sum
}
cout << sum;
return 0;
}
int sumEven=0;
int v[100];
int n;//number of elements you want to enter in the array
do{cout<<"Enter n";
cin>>n;}while(n<=0);
//in a normal 1 dimensional array
for(int i=0;i<n;i++)
if(v[i]%2==0)
sumEven+=v[i];
//in a vector
vector<int> v;
for(vector<int>::iterator it=v.begin();it!=v.end();it++)
if(*it%2==0)
sumEven+=v[i];
Similar to answers above, but if you want to keep the vector of even numbers as well, here are two approaches.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> vec = {1,2,3,4,5,6,7,8,9,10};
// Hold onto what we know is the right answer.
int known_sum = 2+4+6+8+10;
// Copy only even values into another vector
std::vector<int> even_values;
std::copy_if(vec.begin(), vec.end(),
std::back_inserter(even_values),
[](int val){ return val%2==0; });
// Compute sum from even values vector
int even_value_sum = std::accumulate(even_values.begin(), even_values.end(), 0);
// Compute sum from original vector
int even_value_second = std::accumulate(vec.begin(), vec.end(), 0,
[](int current_sum, int new_value) {
return new_value%2==0 ? current_sum + new_value:current_sum;
}
);
// These should all be the same.
std::cout << "Sum from only even vector: " << even_value_sum << std::endl;
std::cout << "Sum from binary op in std accumulate: " << even_value_second << std::endl;
std::cout << "Known Sum: " << known_sum << std::endl;
}
Range-based for loops
A range-based for loop is arguably always a valid alternative to the STL algos, particularly in cases where the operators for the algos are non-trivial.
In C++14 and C++17
E.g. wrapping a range-based even-only accumulating for loop in an immediately-executed mutable lambda:
#include <iostream>
#include <vector>
int main() {
// C++17: omit <int> and rely on CTAD.
const std::vector<int> v{1, 10, 2, 7, 4, 5, 8, 13, 18, 19};
const auto sum_of_even_values = [sum = 0, &v]() mutable {
for (auto val : v) {
if (val % 2 == 0) { sum += val; }
}
return sum;
}();
std::cout << sum_of_even_values; // 42
}
In C++20
As of C++20, you may use initialization statements in the range-based for loops, as well as the ranges library, allowing you to declare a binary comparator in the initialization statement of the range-based for loop, and subsequently apply it the range-expression of the loop, together with the std::ranges::filter_view adaptor:
#include <iostream>
#include <vector>
#include <ranges>
int main() {
const std::vector v{1, 10, 2, 7, 4, 5, 8, 13, 18, 19};
const auto sum_of_even_values = [sum = 0, &v]() mutable {
for (auto is_even = [](int i) { return i % 2 == 0; };
auto val : v | std::ranges::views::filter(is_even)) {
sum += val;
}
return sum;
}();
std::cout << sum_of_even_values; // 42
}
I am new to c++ language. I am trying to solve a problem using function. I have to print the pentagon numbers untill the integer input, but when function returns the values, it only prints one value. I would love some help with it.
#include<iostream>
using namespace std;
int pent(int num){
int p;
for(int i=1;i<=num;i++){
p=(i*(3*i-1)/2);
}
return p;
}
int main(){
int num;
cin>>num;
int sender=pent(num);
cout<<sender<<endl;
return 0;
}
Your function returns int, that is a single integer. To return more, you can use std::vector. As you probably are not familiar with it, I will give you some pointers...
The most simple constructor creates a vector with no entries:
std::vector<int> x;
You can reserve space for elements via reserve:
x.reserve(num);
The vector still has no elements, but it already allocated enough space to hold num elements. This is important, because when we will add elements the vector will grow and that potentially requires to copy all elements to a different place in memory. We can avoid such frequent reallocations by reserving enough space upfront.
To add elements to the vector you can use push_back:
x.push_back(42);
Eventually to print all elements of the vector we can use a range-based for loop:
for (auto element : x) std::cout << element << " ";
So you can rewrite your code like this:
#include <iostream>
#include <vector>
std::vector<int> pent(int num){
std::vector<int> result;
result.reserve(num);
for(int i=1;i<=num;i++){
result.push_back(i*(3*i-1)/2);
}
return result;
}
int main(){
int num;
std::cin >> num;
auto sender = pent(num);
for (auto number : sender) std::cout << number << " ";
}
In your program, from your pent() function you are only returning last calculated value. In you ever time, you are overwriting you variable p.
So there is a way which #asmmo is suggesting, to print in pent() function.
Or you can pass a vector to your pent() function and store values in that and print it in main function.
For your ref:
void pent(int num, vector<int> &arr) {
int p;
for (int i = 1; i <= num; i++) {
arr[i-1] = (i*(3 * i - 1) / 2);
}
}
int main() {
int num;
cin >> num;
vector<int> arr(num);
pent(num, arr);
for (int i = 0; i < num; i++) {
cout << arr[i] << endl;
}
return 0;
}
I'm trying to convert my array to a vector, yet I'm having trouble printing it.
It says in int main() in my for loop that v is undefined. When I define
vector v; inside int main() the program compiles and runs and yet prints nothing. What am I doing wrong?
#include <iostream>
#include <vector>
using namespace std;
vector<int> a2v(int x[], int n)
{
vector<int> v(n);
for(int i = 0; i < n; i++)
{
v.push_back(x[i]);
}
return(v);
}
int main()
{
vector<int> a2v(int x[], int n);
int array[] = {11,12,13,14,15,16,17,18};
a2v(array, 8);
for(int i = 0; i < v.size(); i++)
{
cout << v[i] <<" ";
}
cout << endl;
return(0);
}
This is your program corrected:
#include <iostream>
#include <vector>
using namespace std;
vector<int> a2v(int x[], int n)
{
vector<int> v(0);
v.reserve(n); //optional
for(int i = 0; i < n; i++)
{
v.push_back(x[i]);
}
return(v);
}
int main()
{
int array[] = {11,12,13,14,15,16,17,18};
auto v = a2v(array, 8);
for(size_t i = 0; i < v.size(); i++)
{
cout << v[i] <<" ";
}
cout << endl;
return(0);
}
There were 2 errors:
In the function a2v, you instantiated a vector of 0 with length n, and then you pushed back other elements;
You were not defining v inside the main, as the return value of a2v
The vector you want to read is the return of the a2v function.
But there is a lot more simpler than that to go from C-array to vector array , I put here the example in found the vector reference web page :
http://www.cplusplus.com/reference/vector/vector/vector/
int myints[] = {16,2,77,29};
std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );
When you define a variable, such as your vector v, you always do it in a certain scope. The body of a function such as a2v, or main, is an example of a possible scope. So if you only do it in the function a2v, that's the only scope where it will be visible.
It says in int main() in my for loop that v is undefined.
Well it will be because there is no v in main()
a2v(array, 8);
The above function call returns a vector so you need to collect the returned vector like
vector<int> v=a2v(array,8)
Also,
vector<int> v(n);//creates a vector of size n
for(int i = 0; i < n; i++)
{
v.push_back(x[i]);//adds n more elements to the vector
}
The returned vector has 2n elements and not n
Finally you could directly create a vector from an array as
vector<int> v(arr,arr+n);//where n is the number of elements in arr
I'm beginner in programming. Something is giving me trouble to code. Suppose, I've an array.
int Array[] = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
I want to remove all elements which are greater than 9. How can I do this?
You can do this if you use vector. First initialize vector with your array. Then use remove_if() function. Hope this will help.
#include <algorithm>
#include <vector>
int main()
{
int Array[] = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
vector<int> V(Array, Array+20);
vector<int> :: iterator it;
it = remove_if(V.begin(), V.end(), bind2nd(greater<int>(), 9));
V.erase (it, V.end()); // This is your required vector if you wish to use vector
}
You cannot remove items from an array, since they are fixed in size.
If you used std::vector, then the solution would look like this:
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
std::vector<int> Array = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
Array.erase(remove_if(Array.begin(), Array.end(), [](int n) { return n > 9; }),
Array.end());
copy(Array.begin(), Array.end(), ostream_iterator<int>(cout, " "));
}
Live example: http://ideone.com/UjdJ5h
If you want to stick with your array, but mark the items that are greater than 10, you can use the same algorithm std::remove_if.
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
int Array[] = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
int *overwrite_start = remove_if(std::begin(Array), std::end(Array), [](int n){ return n>9; });
fill(overwrite_start, std::end(Array), -1);
copy(std::begin(Array), std::end(Array), ostream_iterator<int>(cout, " "));
}
The above will move the "erased" items to the end of the array, and mark them with -1.
Live example: http://ideone.com/7rwaXy
Note the usage in both examples of the STL algorithm functions. The second example with the array uses the same remove_if algorithm function. The remove_if returns the start of the "erased" data, as remove_if doesn't actually remove, but moves the data to the end of the sequence.
i am try swap concept without using vector
int Array[] = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
int n;
int arr_len = sizeof(Array)/sizeof(int);
void print_array_value() {
int i;
cout << "\n";
for (i = 0; i < arr_len; i++) {
cout << Array[i] << ", ";
}
cout << " : " << arr_len << "\n";
}
void swap_array_value(int start) {
int i;
for ( ; (start+1) < arr_len; start++) {
Array[start] = Array[start+1];
}
}
void remove_array_value() {
int i;
for (i = 0; i < arr_len; i++) {
if (Array[i] > n) {
swap_array_value(i);
arr_len--;
i--;
}
}
}
void main () {
clrscr();
cout << "Enter the N value : ";
cin >> n;
print_array_value();
remove_array_value();
print_array_value();
cout << "Array Length : " << arr_len;
getch();
}