I have a simple program:
#include <array>
#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;
int main(){
array<int, 5> myArr = {3, 10, 0, 5, 7};
int badNum = 0;
for(int item : myArr){
cout << item << endl;
}
cout << "\n" << endl;
cout << "\n" << endl;
sort(myArr.begin(), myArr.end(), greater<int>());
for(int item : myArr){
cout << item << endl;
}
array<int, 4> goodFour;
for (unsigned int i = 0; i < myArr.size(); i++){
if(myArr[i] != badNum){
// goodThree.append(myArr[i]); <-- This is where I am stuck
}
}
}
I am stuck on trying to assign an element to a std::array. I know in std::vector I can use push_back method, but on a std:array, how to assign to the next (not yet assigned) element? I am coming from Python 3.x where we have the append method for a list. I am not attempting to change the size of the array, instead, I am trying to fill in the allocated spaces with values.
I have looked at:
http://www.cplusplus.com/forum/beginner/67707/
http://www.cplusplus.com/forum/beginner/86394/
http://www.cplusplus.com/forum/beginner/152125/
But these are all for vectors or the primitive int[5] myArr types, not std::array.
If you only want the first three good numbers you would maintain a pointer to the next index to insert at:
for (int i = 0, k = 0; k < 3 && i < myArr.size(); i++) {
if (myArr[i] != badNum) {
goodThree[k++] = myArr[i];
}
}
If you want all the numbers that are good you would use a std::vector and call its push_back method:
std::vector<int> goodThree;
for (int i = 0; i < myArr.size(); i++) {
if (myArr[i] != badNum) {
goodThree.push_back(myArr[i]);
}
}
The size of std::array is fixed at compile time. If you need to append another value at run time, then you have to use std::vector (or something like it). The closest you can get to "appending" to a std::array is if you copy its contents into an array with one more element that contains the "appended" value. You can use some template metaprogramming techniques to make this easier:
template <typename T, std::size_t N, typename X, std::size_t... I>
std::array<T, N + 1> push_back(std::array<T, N> const& a, X&& x, std::index_sequence<I...>) {
return {std::get<I>(a)..., std::forward<X>(x)};
}
template <typename T, std::size_t N, typename X>
std::array<T, N + 1> push_back(std::array<T, N> const& a, X&& x) {
return detail::push_back(a, std::forward<X>(x), std::make_index_sequence<N>());
}
Example of use:
std::array<int, 2> a = {1, 2};
std::array<int, 3> b = push_back(a, 3);
for (int x : b) {
std::cout << x << "\n";
}
The size of a std::array is set at compile time. This means that you cannot "append" values to a std::array at run time. However, you could track how many values your array "contains" by your own program logic. For example:
std::array<int, 5> a = {1, 2, 3, 4, 5};
std::array<int, 4> b;
std::size_t n = 0;
for (int x : a) {
if (x != 2) {
if (n < std::size(a) - 1) {
b[n++] = x;
} else {
throw std::out_of_range("array is full");
}
}
}
Related
The below is the basic code. I want to make the array globally so that i don't have to call it for every function.Now how do I initialize the 2d array with -1. I tried to use memset(arr,-1,sizeof(arr)) just below line 3, but it didn't worked out, so, can anyone tell me what am I doing wrong??
#include <bits/stdc++.h>
using namespace std;
int arr[10][10];
int func(){
//this function will be using the global arr
// if(arr[x][y]!=-1)
//do something
}
int main(){
//the code
}
I do not know the good way to initialize a built-in array in place without code repetition. I do, however, know a way to initialize std::array:
#include <array>
#include <utility>
#include <cstddef>
template<size_t... Ix>
auto constexpr make1array(int v, std::index_sequence<Ix...>) {
auto populate = [](int v, size_t) { return v; };
std::array<int, 10> a = { populate(v, Ix)... };
return a;
}
template<size_t... Ix1, size_t... Ix2>
auto constexpr make2array(int v, std::index_sequence<Ix1...> seq, std::index_sequence<Ix2...>) {
auto populate = [](auto v, size_t) { return v; };
std::array<std::array<int, 10>, 10> a = { populate(make1array(v, seq), Ix2)... };
return a;
}
std::array<std::array<int, 10>, 10> arr = make2array(-1, std::make_index_sequence<10>{}, std::make_index_sequence<10>{});
This code produces an array pre-populated with -1 as the value at compile time.
The function memset won't work because memset uses bytes and many integers occupy more than one byte.
IMHO, your best source is to use std::fill.
Example:
std::fill(&arr[0][0], &arr[9][9] + 1, -1);
Otherwise, you can always fall back on the nested loop:
for (int r = 0; r < MAX_ROWS; ++r)
{
for (int c = 0; c < MAX_COLUMNS; ++c)
{
arr[r][c] = -1;
}
}
Your best bet is to let the compiler optimize the nested loops.
There may be some micro-optimizations that you could employ, but the compiler probably already has them in its tool chest.
There is no direct way to initialize raw array by values that aren't result of default initialization. One of the reasons is that array cannot be returned from function and cannot be assigned directly from anything that is not a {}-list.
Simplest way (since C++14) is to make it part of class-type with constexpr constructor. In C++111 constructor with non-empty body cannot be constexpr.
#include <iostream>
struct MinusOneArray {
static constexpr int NX = 10;
static constexpr int NY = 10;
int arr[NX][NY];
constexpr MinusOneArray() : arr() {
for(int i = 0; i < NX; ++i)
for(int j = 0; j < NY; ++j)
arr[i][j] = -1;
}
};
int main()
{
MinusOneArray a;
auto &arr = a.arr;
for(auto &line: arr) {
for(auto val: line)
std::cout << val << ",";
std::cout << std::endl;
}
}
Alternative is to use standard structure std::array and initialize it with constexpr function, how SergeyA offered.
The question
I am writing a software in c++17 for which performances are absolutely critical. I would like available in a few key functions constants in arrays themselves in arrays. It matters that both these array are accessible by a integer value in such (or similar) manner :
int main()
{
for (int i = 0; i < size_of_A ; i++)
{
for (int j = 0; j < size_of_B_in_A(i); j++)
{
std::cout << A[i][j];
}
}
}
This would be the kind of array we would like to create assuming some function int f(a, b)
A
{
// B1
{
f(1, 1),
f(1, 2),
f(1, 3),
...
f(1, large number)
},
// B2
{
f(2, 1),
...
f(2, some other large number)
},
... etc
}
The Twist
Each inner array may be of different size which we have will stored elsewhere, we have to find the size at compile time. I would rather not use std::vector for they are assumed
slightly slower
.
Also an I suppose a std::vector would be stored on the heap which would be a performance issue in my specific case.
Furthermore,
std::vector cannot be used as "inline constexpr"
which would be necessary as I expect to have a large amount of value in those array never going to change. I am fine with recompiling all those values each time but not keeping them in an external file by policy as I am to follow a strict coding style.
What I Have Tried
brace initializer
// A.hh
#pragma once
#include <iostream>
void test1();
void test2();
inline constexpr int B1[1] = {1};
inline constexpr int B2[2] = {2, 3};
inline constexpr int B3[3] = {4, 5, 6};
inline constexpr const int *A[3] = {B1, B2, B3};
// main.cc
#include "A.hh"
int main()
{
std::cout << "values : ";
for (int i = 0; i < 3; i++)
{
for (int j = 0; j <= i; j++)
{
std::cout << A[i][j];
}
}
std::cout << "\n\naddress test : \n";
std::cout << &A << '\n';
test1();
test2();
}
// somewhere.cc
#include "A.hh"
void test1()
{
std::cout << &A << '\n';
}
// elsewhere.cc
#include "A.hh"
void test2()
{
std::cout << &A << '\n';
}
which prints :
./a.out
values : 123456
address test :
0x56180505cd70
0x56180505cd70
0x56180505cd70
Therefore A has not been copied in main.cc, somewhere.cc and elsewhere.cc which is good. I would like to go further and be able to create a huge amount of values.
struct with constexpr
using tips found
here
, I do this to be able to perform operations during array construction.
// B.hh
#pragma once
#include <iostream>
template <int N>
struct X
{
int arr[N];
constexpr X(): arr()
{
for (int i = 0; i < N; i++)
{
arr[i] = i % 3;
}
}
};
inline constexpr auto A = X<500>();
// main.cc
#include "B.hh"
int main()
{
for (int i = 0; i < 500; i++)
{
std::cout << A.arr[i];
}
}
Which unsuspectingly prints out
012012 (etc)...
Finally an array of array
And this where I am stuck
#pragma once
#include <iostream>
template <int N>
struct sub_array
{
int arr[N];
constexpr sub_array() : arr()
{
for (int i = 0; i < N; i++)
{
arr[i] = i;
}
}
};
struct array
{
sub_array</*what here ?*/> arr[100];
constexpr array() : arr()
{
for (int i = 0; i < 100; i++)
{
int size = i * 2; // a very large number
// the value of 'size' is not usable in a constant expression
//
// I see why it is, but I can't think of any other way
arr[i] = sub_array<size>;
}
}
};
inline constexpr array A = array();
How can I build such kind of array ?
Thank you for your time and consideration.
Just use std::array<std::span<int>, N>, which is a fixed size array of spans of different sizes. To generate this, use an std::index_sequence
Header:
constexpr std::size_t size_of_A = 500;
extern const std::array<const std::span<const int>, size_of_A>& A;
Implementation:
constexpr std::size_t size_of_B_in_A(std::size_t i) { return i%10+1;}
constexpr int f(std::size_t i, std::size_t j) {return static_cast<int>(i%(j+1));}
template <int I, int N>
struct B
{
std::array<int,N> arr;
explicit constexpr B()
{
for (int j = 0; j < N; j++)
arr[j] = f(I, j);
}
constexpr operator const std::span<const int>() const {return {arr};}
};
template<class index_sequence>
class BGen;
template<std::size_t... I>
struct BGen<std::integer_sequence<std::size_t,I...>> {
static constexpr std::tuple<B<I, size_of_B_in_A(I)>...> bs{};
static constexpr std::array<const std::span<const int>, sizeof...(I)> A {std::get<I>(bs)...};
};
const std::array<const std::span<const int>, size_of_A>& A
= BGen<decltype(std::make_index_sequence<size_of_A>{})>::A;
Usage:
int main()
{
for (unsigned i = 0; i < A.size() ; i++)
{
for (unsigned j = 0; j < A[i].size(); j++)
{
std::cout << A[i][j];
}
}
}
http://coliru.stacked-crooked.com/a/d68b0e9fd6142f86
However, stepping back: This solution is NOT the normal way to go about solving this problem. Since it's all constexpr, this is all data not code. Ergo, the most performant solution is two programs. One generates the data and saves it to a file that ships with (inside?) your program. Then your program simply maps the file into memory, and uses the data directly.
Here's a way of implementing a constexpr jagged array which can be initialized without intermediates. It does require listing the row sizes as template arguments, but there are ways to make that easier too, depending on how the row sizes can be known at compile time.
#include <tuple>
#include <array>
#include <utility>
template <std::size_t ...Sizes>
struct jagged_array
{
const std::tuple<std::array<int,Sizes>...> data;
static constexpr std::size_t num_rows = sizeof...(Sizes);
static constexpr std::size_t length[num_rows]{Sizes...};
int const* const row_ptr[num_rows];
template <std::size_t ...I>
constexpr jagged_array(std::index_sequence<I...>,
const std::array<int, Sizes>& ...arrs)
: data{arrs...}, row_ptr{&std::get<I>(data)[0]...} {}
constexpr jagged_array(const std::array<int, Sizes>& ...arrs)
: jagged_array(std::make_index_sequence<num_rows>{}, arrs...)
{}
constexpr int const* operator[](std::size_t idx) const
{ return row_ptr[idx]; }
};
inline constexpr jagged_array<2,4> jarr = {{2,3}, {4,5,6,7}};
Write a function which will take two arrays as parameters and add the individual
elements of each array together such that firstArray[i] = firstArray[i] +
secondArray[i] where 0 <= i <= 4.
int[] sumEqualLengthArrays(int[] a, int[] b) {
int[] result = new int[a.length];
for (int i = 0; i < a.length; i++)
result[i] = a[i] + b[i];
return result;
}
I have been stuck on this for a while now and I just can't get my head around what the answer is. I have attempted to answer it in the code above. I am a beginner to C++ programming as I am studying it in my free time. An answer to this question would really help!
Since you said you can use anything, Use std::vector with std::transform and std::plus<int>(). something like this :
std::transform (a.begin(), a.end(), b.begin(), a.begin(), std::plus<int>());
If you insist on using normal arrays (here assume a and b are arrays) then you can do something like this :
std::transform(a, &a[number_of_elements], b, a, std::plus<int>());
But please, don't.. Use std::vector.
How to use first approach :
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> a = {1, 2, 3};
std::vector<int> b = {1, 2, 3};
std::transform(a.begin(), a.end(), b.begin(), a.begin(), std::plus<int>());
for(auto iter = a.begin(); iter != a.end(); ++iter)
{
std::cout << *iter << std::endl;
}
return 0;
}
How to use second approach :
#include <iostream>
#include <algorithm>
int main()
{
int a[3] = {1, 2, 3};
int b[3] = {1, 2, 3};
std::transform(a, &a[0] + 3, b, a, std::plus<int>());
for(int i = 0; i < 3; ++i)
{
std::cout << a[i] << std::endl;
}
return 0;
}
Something like this:
std::vector<int> sumEqualLengthArrays(const std::vector& rhs,
const std::vector& lhs){
if(lhs.length() == rhs.length()){
std::vector<int> result(rhs.length(), 0);
for(unsigned int i = 0; i < rhs.length; ++i){
result[i] = rhs[i] + lhs[i];
}
return result;
}else{
std::cout << "Length is not equal!" << std::endl;
return rhs;
}
}
I would advise to use vectors instead of arrays and check the length before usage just in case to avoid errors.
You've written the summing expression already in the problem formulation. If you look at it once again, you'll see that the result is stored in first and there's no need in separate result array (returning an array is not a trivial thing in C++).
And, speaking of which, passing arrays as arguments is not easy either.
Assuming, you don't use std::vector, simple options are as follows.
int a[] (note the position of square brackets) as a function formal argument is synonymous to a pointer. It does not contain any size information, so you'll have to add a third argument which is the minimal size of both arrays:
int *add(int a[], int b[], std::size_t commonSize) { // commonSize is the least of a's and b's sizes
for(std::size_t i = 0; i < commonSize; ++i) a[i] += b[i];
return a;
}
You can deduce array's size when passed by reference, this is allowed in C++ and is a serious deviation from classic C:
template<std::size_t A, std::size_t B> int (&add(int (&a)[A], int (&b)[B]))[A] {
for(std::size_t i = 0; i < std::min(A, B); ++i) a[i] += b[i];
return a;
}
Then the common size is the minimum of A and B.
You can use std::array, this is almost the same as previous option
template<std::size_t A, std::size_t B> void add(std::array<int, A> &a, std::array<int, B> const &b);
This way you can even use range-for loops, or, for instance, STL algorithms (which tend to acquire parallelized and non-sequential overloads recently), though it requires a small amount of additional work (which is a bit too large to fit in this margin).
Problem: I want to get an array A[6] = {6, 5, 4, 3, 2, 1} to be A[6] = {5, 3, 1, 1, 1, 1}. In other words - "delete" every second value starting with 0th and shift all other values to the left.
My Attempt:
To do that I would use this code, where a - length of the relevant part of an array A (the part with elements that are not deleted), ind - index of the value that I want to delete.
for (int j = ind; j < n; j++)
A[j] = A[j+1];
However, I couldn't get this to work, using the code like that:
void deleting(int A[], int& a, int ind){
for (int j = ind; j < a; j++)
A[j] = A[j+1];
a--;
}
int A[6] = {6, 5, 4, 3, 2, 1};
a = 6
for (int i = 0; i < a; i+=2)
deleting(A, a, i);
After running this code I was getting A[6] = {5, 4, 2, 1, 1507485184, 1507485184}. So, it deleted the elements at indexes 0, 3. Why did it delete the 3rd index?
There are two ways to do this:
walk the array, copying the last n-i elements forward one place for every even i, or
figure out the eventual state and just go straight to that. The eventual state is the first n/2 places are array[i]=array[2*i + 1], and the last n/2 places are just copies of the last element.
The first method is what you asked for, but it does multiple redundant copy operations, which the second avoids.
As for your implementation problems, examine what happens when j=n-1, and remember A[n] is not a valid element of the array.
I suggest making the copy-everything-forward operation its own function anyway (or you can just use memcpy)
For these kinds of problems (in-place array manipulation), it's a good idea to just keep an index or pointer into the array for where you are "reading" and another where you are "writing." For example:
void odds(int* a, size_t len) {
int* writep = a;
int* readp = a + 1;
while (readp < a + len) { // copy odd elements forward
*writep++ = *readp;
readp += 2;
}
while (writep < a + len - 1) { // replace rest with last
*writep++ = a[len - 1];
}
}
Just for kicks, here is a version which doesn't use a loop:
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <utility>
#include <initializer_list>
template <typename T, std::size_t Size>
std::ostream& print(std::ostream& out, T const (&array)[Size]) {
out << "[";
std::copy(std::begin(array), std::end(array) -1,
std::ostream_iterator<T>(out, ", "));
return out << std::end(array)[-1] << "]";
}
template <std::size_t TI, std::size_t FI, typename T, std::size_t Size>
bool assign(T (&array)[Size]) {
array[TI] = array[FI];
return true;
}
template <typename T, std::size_t Size,
std::size_t... T0>
void remove_even_aux(T (&array)[Size],
std::index_sequence<T0...>) {
bool aux0[] = { assign<T0, 2 * T0 + 1>(array)... };
bool aux1[] = { assign<Size / 2 + T0, Size - 1>(array)... };
}
template <typename T, std::size_t Size>
void remove_even(T (&array)[Size]) {
remove_even_aux(array, std::make_index_sequence<Size / 2>());
}
int main() {
int array[] = { 6, 5, 4, 3, 2, 1 };
print(std::cout, array) << "\n";
remove_even(array);
print(std::cout, array) << "\n";
}
If C++ algorithms are an option, I tend to prefer them by default:
auto *const end_A = A + (sizeof(A)/sizeof(*A));
auto *new_end = std::remove_if(
A, end_A,
[&A](int const& i) { return (&i - A) % 2 == 0; });
// Now "erase" the remaining elements.
std::fill(new_end, end_A, 0);
The std::remove_if algorithm simply moves the elements that do not match the predicate (in our case, test if the address is MOD(2)=0), and std::moves them to the end. This is in place. The new "end" is return, which I then indexed over and set the elements to 0.
So if it has to be an array the solution would be like this:
void deleting(int A[size], int size){
for (int i = 0; i < size / 2; i++)
A[i] = A[2 * i + 1];
for (int i = size / 2; i < size; i++)
A[i] = A[size / 2];
}
You first loop through first half of the array "moving" every second number to the front, and then you loop through the rest filling it with the last number.
For a more versatile version of other's answers:
#include <iostream>
template<typename InputIt, typename T>
void filter(InputIt begin, InputIt end, T const& defaultvalue)
{
InputIt fastforward = begin;
InputIt slowforward = begin;
fastforward++; // starts at [1], not [0]
while (fastforward < end)
{
*slowforward = *fastforward;
++slowforward;
++ ++fastforward;
}
while (slowforward < end) // fill with default value
{
*slowforward++ = defaultvalue;
}
}
int main()
{
int A[6] = {6, 5, 4, 3, 2, 1};
std::cout << "before: ";
for (auto n : A)
std::cout << n << ", ";
std::cout << std::endl;
filter(A, A+6, 1);
std::cout << "after: ";
for (auto n : A)
std::cout << n << ", ";
std::cout << std::endl;
}
Outputs:
before: 6, 5, 4, 3, 2, 1,
after: 5, 3, 1, 1, 1, 1,
And this works with std::array<bool>, std::vector<std::string>, std::unordered_set<void*>::iterator, etc.
The common way of doing this would be keeping two indices: one to the entry you're modifying and the other to the entry you intend to process
const auto size = sizeof(A) / sizeof(int);
// N.b. if size == 1 entire array is garbage
int i = 0;
for (int nv = 1; nv < size; ++i, nv += 2)
A[i] = A[nv];
--i;
// Significative array is now [0;N/2[, fill with last now
for (int j = i + 1; j < size; ++j)
A[j] = A[i];
This grants an in-place-modify fashion.
you can combine std::remove_if and std::fill to do this
example code:
#include <algorithm>
#include <iostream>
#include <iterator>
int main()
{
int A[6] = {6, 5, 4, 3, 2, 1};
auto endX = std::remove_if(std::begin(A),std::end(A),[&A](const int& i){return (&i-A)%2==0;});
if(endX!=std::begin(A))//in case nothing remained, although not possible in this case
std::fill(endX,std::end(A),*(endX-1));
//else /*something to do if nothing remained*/
for(auto a : A)std::cout<<a<<' ';
}
Instead of typing
array[0] + array[1] //.....(and so on)
is there a way to add up all the numbers in an array? The language I'm using would be c++
I want to be able to do it with less typing than I would if I just typed it all out.
Here is the idiomatic way of doing this in C++:
int a[] = {1, 3, 5, 7, 9};
int total = accumulate(begin(a), end(a), 0, plus<int>());
Note, this example assumes you have somewhere:
#include <numeric>
using namespace std;
Also see: accumulate docs and accumulate demo.
Say you have an int array[N].
You can simply do:
int sum = 0;
for(auto& num : array)
sum += num;
Try this:
int array[] = {3, 2, 1, 4};
int sum = 0;
for (int i = 0; i < 4; i++) {
sum = sum + array[i];
}
std::cout << sum << std::endl;
If you use a valarray, there is a member function sum() for that.
#include <iostream> // std::cout
#include <valarray> // std::valarray
int main () {
std::valarray<int> myvalarray(4);
myvalarray[0] = 0;
myvalarray[1] = 10;
myvalarray[2] = 20;
myvalarray[3] = 30;
std::cout << "The sum is " << myvalarray.sum() << '\n';
return 0;
}
The easiest way I can see to do this is to use a loop. The bonus is that you can use it on any integer array without rewriting much code at all. I use Java more often, so I hope there aren't too many syntax errors, but something like this should work:
int addArray(int[] array, int length){
int sum=0;
for(int count=0;count<length;count++){
sum+=array[count];
}
return sum;
}
In C++17, one could use fold expressions:
template<typename ...Ts>
int sum_impl(Ts&& ...a)
{
return (a + ...);
}
If sum_impl had a constant number of parameters, we could have called it like this:
std::apply(sum_impl, arr);
assuming arr is std::array<int, N>. But since it is variadic, it needs a little push with helpers:
using namespace std;
template <class Array, size_t... I>
int sum_impl(Array&& a, index_sequence<I...>)
{
return sum_impl(get<I>(forward<Array>(a))...);
}
template <class Array>
int sum(Array&& a)
{
return sum_impl(forward<Array>(a),
make_index_sequence<tuple_size_v<decay_t<Array>>>{});
}
Therefore, assuming these helpers are in place, the code will look something like this:
template<typename ...Ts>
int sum_impl(Ts&& ...a)
{
return (a + ...);
}
int main()
{
array<int, 10> arr{0,1,2,3,4,5,6,7,8,9};
cout << sum(arr) << "\n";
return 0;
}
We may use user defined function.
Code Snippet :
#include<bits/stdc++.h>
using namespace std;
int sum(int arr[], int n)
{
int sum=0;
for(int i=0; i<n; i++)
{
sum += arr[i];
}
return sum;
}
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = distance(begin(arr), end(arr));
int total = sum(arr,n);
printf("%d", total);
return 0;
}
int Sum;
for(int& S: List) Sum += S;
If your compiler supports c++17, you may use a combination of Parameter pack and fold expression to achieve this. A template parameter pack is a template parameter that accepts zero or more template arguments, and fold reduces the parameter pack over a binary operator. (+ in this case)
#include <iostream>
#include <array>
#include <utility>
/*
* References:
* [1] https://en.cppreference.com/w/cpp/language/fold
* [2] https://en.cppreference.com/w/cpp/language/parameter_pack
*/
template <typename ...T>
auto sum(T ...args)
{
return (args + ...);
}
template <typename T, std::size_t ...Is>
auto sum(T t, std::index_sequence<Is...>)
{
return sum(t[Is]...);
}
int main()
{
std::array<int, 3> a1 = {1, 4, 3};
int a2[5] = {1, 2, 3, 4, 0};
std::cout << "Sum a1 = " << sum(a1, std::make_index_sequence<a1.size()>{}) << "\n";
std::cout << "Sum a2 = " << sum(a2, std::make_index_sequence<5>{}) << "\n";
return 0;
}
Adding one more point regarding std::accumulate usage:
When a C-style array is passed to a function then you should explicitly specify the array start and end(one-past-the-end) addresses when you use the std::accumulate.
Example:
#include <numeric>
void outsideFun(int arr[], int n) {
int sz = sizeof arr / sizeof arr[0]; // 1=decays to a ptr to the 1st element of the arr
// int sum = accumulate(begin(arr), end(arr), 0); // Error:begin/end wouldn't work here
int sum = accumulate(arr, arr + n, 0); // 15 (Method 2 Only works!)
std::cout << sum;
}
int main() {
int arr[] = { 1,2,3,4,5 };
int sz = sizeof arr / sizeof arr[0]; // 5
int sum = accumulate(begin(arr), end(arr), 0); // 15 (Method 1 - works)
int cum = accumulate(arr, arr + sz, 0); // 15 (Method 2 - works)
outsideFun(arr, sz);
}