using std::accumulate when there is pointer - c++

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;
}

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};

Related

C++ creating a vector which stores different typenames

I want to create a vector which stores name of data types(int,char,bool,etc)
I am looking for something like:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(int argc,char** argv)
{
vector<typenames> v = {int,float,double,bool};
}
If you have a finite set of types you want to store, you can use <variant>, e.g.
#include <variant>
using VarType = std::variant<int, float, double, bool>;
std::vector<VarType> v;
v.push_back(42);
assert(std::holds_alternative<int>(v.front()));
assert(std::get<int>(v.front()) == 42);
v[0] = true;
assert(std::holds_alternative<bool>(v.front()));
assert(std::get<bool>(v.front()));
Note that if C++17 is not available, you can go with Boost variant.
No. It's not possible. C++ is a statically-typed language, not a dynamic-typed language. What you can do is have set of enums, for types and put them into vector.
enum Type
{
IntType, FloatType, DoubleType, BoolType
};
vector<Type> v;
Or you can use std::variant (C++17).
Your question wasn't clear. Maybe you need std::pair or std::tuple to keep different items (with a defined number of elements).

Elegant way to push back std::array to std::vector N times

the following codes pushed back an std::array to a std::vector N times. Is there a more elegant and shorter way of doing this?
#include <iostream>
#include <vector>
#include <array>
#include <iomanip>
#include <complex>
#include <cmath>
int main () {
int N=10;
std::vector< std::array<std::complex<double>,3> > v;
v.reserve(N);
for(int i=0;i<N;i++){
std::array<std::complex<double>,3> el { {0.0,3.0,0.0} };
v.push_back(el);
}
}
Yes but you have to use parentheses when constructing vector
std::vector< std::array<std::complex<double>,3> > v(n, {0.0,3.0,0.0});
If braces are used than initialization list is preferred and in this case you could have unexpected errors.
You can use the std::vector::insert (#3 in the overload set) member function:
int N=10;
std::vector< std::array<std::complex<double>,3> > v;
v.reserve(N);
v.insert(v.end(), N, { {0.0,3.0,0.0} });
Note that #MarekR's answer is preferable for initializing the vector, as it circumvents the call to reserve, and setting up an object during initialization is usually better than subsequent member function calls. The above call to std::vector::insert instead is suitable for adding additional elements later on.

How to sort vector of struct C++ [duplicate]

This question already has answers here:
Standard library sort and user defined types
(3 answers)
Closed 8 years ago.
I'm trying to sort vector of struct, but it ends with error. I tried to do it according to C++ reference, but I don't know where the problem is. Could someone help me?
#include <cstdlib>
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
/*
*
*/
struct reg{
string name;
string addr;
};
int main(int argc, char** argv) {
vector <reg> a;
reg newReg = { "John", "Street1"};
a.push_back(newReg);
reg newReg2 = { "Mike", "Street2"};
a.push_back(newReg2);
std::sort (a.begin(), a.end());
return 0;
}
Unlike build-in types like int, float etc, you have to define the compare function for struct reg, i.e. rules that you want the elements to follow when sorting. Like this:
bool my_compare(const struct reg &x, const struct reg &y)
{
// define how to compare x,y here
}
And then, you can pass this function to sort the vector:
std::sort (a.begin(), a.end(), my_compare);
You either have to overload the comparison operator (less than, afair) or provide a custom comparison function.
You need to tell std::sort what makes one instance of the struct "less than" another instance of the struct.
In other words, if I give you two instances of those structs filled with data, and ask you "which one is placed before the other?", what is your answer? The rules you used to come with that answer is what you need to code and give to the 3 argument version of std::sort.

assign multiple values to boost::numeric::ublas::vector in c++

I want to know how I can assign multiple values to a vector at once:
#include <iostream>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>
using namespace boost::numeric::ublas;
int main()
{
vector<double> v1(3);
v1(0)=0;
v1(1)=0.1;
v1(2)=0.05;
v1(3)=0.25;
return 0;
}
I want to assign all the values at once.
something like:
v1 << 0,0.1,0.05,0.25;
I tried operator += and there is an error, but I think operator += works for std::vector not boost::....vector
Take a look at documentation examples http://svn.boost.org/svn/boost/trunk/libs/numeric/ublas/doc/samples/assignment_examples.cpp
Basically, you need v1 <<= 0, 1, 2;, see more examples in the docs. Unfortunately this library doesn't support initializer_list's yet: http://boost.2283326.n4.nabble.com/Initializing-from-an-initializer-list-td4647029.html

How can I initialize a SparseVector in Eigen

How can I initialize a SparseVector in Eigen ? The following code:
#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET
#include <Eigen/Sparse>
using namespace Eigen;
SparseVector<float> vec(3);
main()
{
vec(0)=1.0;
}
gives me the following error
error: call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type
vec(0)=1.0;
by the way, vec[0]=1.0 doesn't work either.
Looking at the documentation I noticed Scalar& coeffRef(Index i), and it says:
Returns a reference to the coefficient value at given index i. This operation involes a log(rho*size) binary search. If the coefficient does not exist yet, then a sorted insertion into a sequential buffer is performed. (This insertion might be very costly if the number of nonzeros above i is large.)
So the following should work:
#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET
#include <Eigen/Sparse>
using namespace Eigen;
SparseVector<float> vec(3);
main()
{
vec.coeffRef(0)=1.0;
}
Not sure why they did it that way instead of using array overloading. Perhaps when it becomes IS_STABLE then they'll do it in a more typical C++ way?