0

Is this the only solution when there is a pointer that points to a vector and we would like to use accumulate to sum up numbers? Is there any simpler solution rather than writing a lambda function and using a four argument type of accumulating?

Also, for using std::sort, will the situation be the same?

Here is the code:

#include <random>
#include <vector>
#include <iostream>
#include<bits/stdc++.h>
using namespace std;

int main() {
    
    const int N=3; 

    auto  p=make_unique<array<int,N>> ();
    
    (*p)[0]=3;
    (*p)[1]=4;
    (*p)[2]=5;
    
    sum=accumulate(p,?,0); 
    
    

    return 0;
}
MA19
  • 510
  • 3
  • 15
  • 3
    Your scenario is different than the linked question if it is as you described. The linked question discusses accumulation a vector of *pointers*; you seem to be asking how to accumulate from **a** pointer to **a** vector (of. something). Actual *real* code showing what you have, and what you're trying to do, is warranted if you want a *real* answer. – WhozCraig Feb 13 '21 at 21:45
  • 1
    If you have a `vector`, you have no choice but to use a lambda. If you want to accumulate a `vector*`, then you can use `std::accumulate(ptr->begin(), ptr->end(),0)`. Please clarify your use case with a code snippet. – Mansoor Feb 13 '21 at 21:48
  • 1
    @MAero2020 So it's like M.A said `std::accumulate(p->begin(), p->end(),0)` and the same idea will work for `std::sort`. – john Feb 13 '21 at 21:53
  • @M.A sorry, I added the code snippet – MA19 Feb 13 '21 at 21:53
  • 2
    You do realize there's no vector in the code you posted... – Blastfurnace Feb 13 '21 at 21:55
  • @Blastfurnace Also `const N=3;` is illegal. Probably a case of not the real code. – john Feb 13 '21 at 21:56
  • 2
    [Here's your code](https://godbolt.org/z/86aj1a) with syntax errors corrected and the correct include headers. Are you learning C++ from online tutorials or "competitive programming" sites? You might want a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Blastfurnace Feb 13 '21 at 22:05
  • @Blastfurnace Thanks for the book! I am learning C++ through online tutorials – MA19 Feb 13 '21 at 22:11
  • 1
    Unfortunately there's a **lot** of questionable content out there. Not everyone is suited to learning from books but I think the structure of a book is good for the language fundamentals. – Blastfurnace Feb 13 '21 at 22:14

1 Answers1

1

To answer your immediate question:

std::accumulate(p->begin(), p->end(), 0);

The same syntax will work for other STL algorithms as well.


Other improvements to your code snippet:

Avoid using #include<bits/stdc++.h>, see this post. Similarly for using namespace std, it's considered bad practise.

const N=3 -> const auto N=3

std::array is not a vector and you can initialise it directly using initializer-list syntax:

const auto* obj = new std::array<int,3>{3,4,5};
Mansoor
  • 2,357
  • 1
  • 17
  • 27