patterncppMinor
Squaring numbers in an array
Viewed 0 times
arraynumberssquaring
Problem
I want to know if there is a better way to square numbers in an array. This is what I wrote:
#include
using std::cout;
using std::endl;
void square(int []);
int main()
{
int array[] = {2,4,6,8,10};
square(array);
for(auto i : array)
cout << i << " ";
}
void square(int array[])
{
int size = sizeof(array)/sizeof(array[0]);
for(int i=0; i< size; i++)
array[i] *= array[i];
}Solution
-
Just so you know,
-
You can use a vector instead of an array.
in place of a function object:
int size = sizeof(array)/sizeof(array[0]);Just so you know,
sizeof() returns size_t.-
You can use a vector instead of an array.
vector data = {2,4,6,8,10};- Simplify squaring using
std::transform()and use a lambda expression
in place of a function object:
#include
#include
#include
using std::cout;
using std::transform;
using std::vector;
int main()
{
vector data = {2,4,6,8,10};
transform(data.begin(), data.end(), data.begin(), [](int x){return x*x;});
for(auto i : data)
cout << i << " ";
}Code Snippets
vector<int> data = {2,4,6,8,10};#include <iostream>
#include <algorithm>
#include <functional>
using std::cout;
using std::transform;
using std::vector;
int main()
{
vector<int> data = {2,4,6,8,10};
transform(data.begin(), data.end(), data.begin(), [](int x){return x*x;});
for(auto i : data)
cout << i << " ";
}Context
StackExchange Code Review Q#66594, answer score: 5
Revisions (0)
No revisions yet.