I'm trying to use a boost accumulator to calculate a rolling mean. When I declare the variable inline like this:
#include <iostream>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/rolling_mean.hpp>
using namespace boost::accumulators;
int main()
{
// Define rolling_mean accumulator
accumulator_set<double, stats<tag::rolling_mean > > acc(tag::rolling_window::window_size = 5);
// push in some data ...
acc(1.2);
acc(2.3);
acc(3.4);
acc(4.5);
// Display the results ...
std::cout << "Mean: " << rolling_mean(acc) << std::endl;
return 0;
}
It works just fine. When I declare the accumulator as a member of a class like so:
#include <iostream>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/rolling_mean.hpp>
using namespace boost::accumulators;
class DoMean {
private:
accumulator_set<double, stats<tag::rolling_mean > > m_acc(tag::rolling_window::window_size = 5);
public:
void addData(double val) {
this->m_acc(val);
}
double getMean(void) {
return rolling_mean(this->m_acc);
}
};
int main()
{
// Define an accumulator set for calculating the mean and the
// 2nd moment ...
DoMean meaner;
meaner.addData(1.2);
meaner.addData(2.3);
meaner.addData(3.4);
meaner.addData(4.5);
// push in some data ...
// Display the results ...
std::cout << "Mean: " << meaner.getMean() << std::endl;
return 0;
}
It fails, giving the compiler errors:
accumulators::tag::rolling_window::window_size is not a type
...blah blah, many type template errors etc.
The correct solution to this problem is this:
#include <iostream>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/rolling_mean.hpp>
using namespace boost::accumulators;
class DoMean {
private:
accumulator_set<double, stats<tag::rolling_mean > > m_acc;
public:
DoMean(void): m_acc(tag::rolling_window::window_size = 5) {}
void addData(double val) {
this->m_acc(val);
}
double getMean(void) {
return rolling_mean(this->m_acc);
}
};
int main()
{
// Define an accumulator set for calculating the mean and the
// 2nd moment ...
DoMean meaner;
meaner.addData(1.2);
meaner.addData(2.3);
meaner.addData(3.4);
meaner.addData(4.5);
// push in some data ...
// Display the results ...
std::cout << "Mean: " << meaner.getMean() << std::endl;
return 0;
}
Notice that the initialization of m_acc has been moved from inline with it's declaration, into the initialization list. This solves all the compiler errors. In fact, if we think about what's happening here, the reason that the initial attempt at using the accumulator in a class fails is because ISO c++ forbids initialization of members inline.
We can demonstrate this with another simple class:
#include <iostream>
class TestInit {
public:
int m_init = 10;
};
int main() {
TestInit inits;
std::cout << "The value: " << inits.m_init << std::endl;
}
Now the compiler gives us a helpful message:
/home/me/prog/cpp/acctest/testinit.cxx:5:16: error: ISO C++ forbids initialization of member m_init [-fpermissive]
/home/me/prog/cpp/acctest/testinit.cxx:5:16: error: making m_init static [-fpermissive]
/home/me/prog/cpp/acctest/testinit.cxx:5:16: error: ISO C++ forbids in-class initialization of non-const static member m_init
Related
The code below is giving the error: Call to deleted constructor of 'std::unique_ptr<int>' 'unique_ptr' has been explicitly marked deleted here passing argument to parameter 'item' here.
Could someone please explain why this is? I would have thought everything would be fine because I'm using std::move in the call to foo.add.
#include <iostream>
#include <memory>
#include <set>
class Foo {
public:
void add(std::unique_ptr<int> item) {
set.emplace(std::move(item));
}
private:
std::set<std::unique_ptr<int>> set;
};
int main() {
Foo foo;
std::set<std::unique_ptr<int>> set;
set.emplace(std::make_unique<int>(1));
set.emplace(std::make_unique<int>(2));
set.emplace(std::make_unique<int>(3));
for (auto &item : set) {
foo.add(std::move(item)); // error on this line
}
return 0;
}
Use c++ 17 extract() function.
example
#include <set>
#include <memory>
#include <iostream>
int main() {
auto s = std::set<std::unique_ptr<int>>{};
s.insert(std::make_unique<int>(10));
std::cout << s.size() << "\n";
auto it = s.extract(s.begin());
// Pointer type here just for clarification
std::unique_ptr<int> new_ptr = std::move(it.value());
std::cout << s.size() << "\n";
std::cout << *new_ptr << "\n";
}
Then instead of your for each loop you might use a while loop:
while (!set.empty()) {
auto it = set.extract(set.begin());
foo.add(std::move(it.value());
}
#include <iostream>
#include <cstdlib>
namespace A {
int a = 10;
void get_value(){ std::cout << "a = " << a << std::endl; }
}
namespace B {
int b;
void get_value(){ std::cout << "b =" << b << std::endl; }
}
void set_B();
int main(){
using namespace A;
get_value();
set_B();
system("PAUSE");
return 0;
}
void set_B(){
using namespace B;
b = 15;
get_value(); // Why call to get_value() is ambiguous, error is not generated here ?
}
Why call to get_value() inside set_B() function is not ambiguous ( A::get_value() or B::get_value()) as both appear as ::get_value() inside set_B().
using namespace A; isn't active inside set_B because it only appears inside main. It is limited to the scope in which it appears: the body of main.
because A::get_value and B::get_value arn't normally visible in the global scope. the using namespace statement makes the declarations in that namespace visible inside set_B.
This may be a really easy question but... here it goes. (Thanks in advance!)
I am simplifying the code so it is understandable. I want to use a variable calculated inside another class without running everything again.
source.ccp
#include <iostream>
#include "begin.h"
#include "calculation.h"
using namespace std;
int main()
{
beginclass BEGINOBJECT;
BEGINOBJECT.collectdata();
cout << "class " << BEGINOBJECT.test;
calculationclass SHOWRESULT;
SHOWRESULT.multiply();
system("pause");
exit(1);
}
begin.h
#include <iostream>
using namespace std;
#ifndef BEGIN_H
#define BEGIN_H
class beginclass
{
public:
void collectdata();
int test;
};
#endif
begin.cpp
#include <iostream>
#include "begin.h"
void beginclass::collectdata()
{
test = 6;
}
calculation.h
#include <iostream>
#include "begin.h"
#ifndef CALCULATION_H
#define CALCULATION_H
class calculationclass
{
public:
void multiply();
};
#endif
calculation.cpp
#include <iostream>
#include "begin.h"
#include "calculation.h"
void calculationclass::multiply()
{
beginclass BEGINOBJECT;
// BEGINOBJECT.collectdata(); // If I uncomment this it works...
int abc = BEGINOBJECT.test * 2;
cout << "\n" << abc << endl;
}
Simply define member function multiply as
void calculationclass::multiply( const beginclass &BEGINOBJECT ) const
{
int abc = BEGINOBJECT.test * 2;
cout << "\n" << abc << endl;
}
And call it as
int main()
{
beginclass BEGINOBJECT;
BEGINOBJECT.collectdata();
cout << "class " << BEGINOBJECT.test;
calculationclass SHOWRESULT;
SHOWRESULT.multiply( BEGINOBJECT );
system("pause");
exit(1);
}
In your code beginclass has no explicit constructor, hence the implicitly defined default constructor will be used, which default constructs all members. Hence, after construction beginclass::test is either 0 or uninitiliased.
What you appear to be wanting is to avoid to call beginclass::collectdata() more than once. For this you would want to set a flag that remembers if beginclass::collectdata() has been called. The member function which returns the data then first checks this flags and, if the flag was not set, calls beginclass::collectdata() first. See also the answer by CashCow.
It looks like you are looking for some kind of lazy evaluation / caching technique whereby a value is calculated the first time it is requested then stored to return it subsequently without having to reevaluate.
In a multi-threaded environment the way to achieve this (using the new standard thread library) is by using std::call_once
If you are in a single-threaded environment, and you just want to get a value out of a class, use a getter for that value. If it isn't calculated in a "lazy" fashion, i.e. the class calculates it instantly, you can put that logic in the class's constructor.
For a "calc_once" example:
class calculation_class
{
std::once_flag flag;
double value;
void do_multiply();
double multiply();
public:
double multiply()
{
std::call_once( flag, do_multiply, this );
return value;
}
};
If you want multiply to be const, you'll need to make do_multiply also const and value and flag mutable.
I've just made a template to detect if a data member of a class is static defined or not. The accessibility of the member isn't what it should be concerned about(Assuming the member is always accessible by the template) in this post. Here is the code with any symbols for testing:
#include <conio.h>
//#include <stdio.h>
#include <iostream>
struct A1
{
int a;
};
struct A2
{
static int a;
};
int A2::a{};
template < class My_Type >
struct TestStatic
{
template < typename raw_ty > static char fTest(...);
template < typename class_ty, typename arg_ty = decltype(class_ty::a) >
static int fTest(int, arg_ty & = class_ty::a);
enum nRes { result = sizeof(fTest<My_Type>(0)) - 1 };
};
int main(void)
{
int i;
i = TestStatic<A1>::result;
std::cout << i << std::endl;
i = TestStatic<A2>::result;
std::cout << i << std::endl;
_getch();
return(0);
}
The question is when it was built with g++ 4.8 the compiling passed but got the result as two '3's rather than one '0' and another '3'. Is there anything wrong?
Your approach is fundamentally flawed, because decltype(T::x) is perfectly valid for non-static members:
#include <iostream>
struct T
{
int x;
};
int main()
{
std::cout << sizeof(decltype(T::x)) << '\n';
}
// Output: 4
You can get what you want with std::is_member_pointer:
If T is pointer to non-static member object or a pointer to non-static member function, provides the member constant value equal true. For any other type, value is false.
#include <iostream>
#include <type_traits>
struct T
{
int x;
};
struct S
{
static int x;
};
int main()
{
std::cout << !std::is_member_pointer<decltype(&T::x)>::value << ' ';
std::cout << !std::is_member_pointer<decltype(&S::x)>::value << '\n';
}
// Output: 0 1
This works because access to members through the :: syntax results in a pointer-to-member only if the member is not-static; it is of course a normal variable access when the member is static.
I'm working on a homework assignment for my C++ class and have ran across a problem that I cannot figure out what I am doing wrong.
Just to note, the separation of the files is necessary and I realize this would be much easier if I just made a structure AttackStyles inside the main and forgo the additional class file altogether.
The base of my problem is that I cannot seem to be able to loop through an array of classes and pull out base data. Here is the code:
// AttackStyles.h
#ifndef ATTACKSTYLES_H
#define ATTACKSTYLES_H
#include <iostream>
#include <string>
using namespace std;
class AttackStyles
{
private:
int styleId;
string styleName;
public:
// Constructors
AttackStyles(); // default
AttackStyles(int, string);
// Destructor
~AttackStyles();
// Mutators
void setStyleId(int);
void setStyleName(string);
// Accessors
int getStyleId();
string getStyleName();
// Functions
};
#endif
/////////////////////////////////////////////////////////
// AttackStyles.cpp
#include <iostream>
#include <string>
#include "AttackStyles.h"
using namespace std;
// Default Constructor
AttackStyles::AttackStyles()
{}
// Overloaded Constructor
AttackStyles::AttackStyles(int i, string n)
{
setStyleId(i);
setStyleName(n);
}
// Destructor
AttackStyles::~AttackStyles()
{}
// Mutator
void AttackStyles::setStyleId(int i)
{
styleId = i;
}
void AttackStyles::setStyleName(string n)
{
styleName = n;
}
// Accessors
int AttackStyles::getStyleId()
{
return styleId;
}
string AttackStyles::getStyleName()
{
return styleName;
}
//////////////////////////////////////////////
// main.cpp
#include <cstdlib>
#include <iostream>
#include <string>
#include "attackStyles.h"
using namespace std;
int main()
{
const int STYLE_COUNT = 3;
AttackStyles asa[STYLE_COUNT] = {AttackStyles(1, "First"),
AttackStyles(2, "Second"),
AttackStyles(3, "Third")};
// Pointer for the array
AttackStyles *ptrAsa = asa;
for (int i = 0; i <= 2; i++)
{
cout << "Style Id:\t" << ptrAsa->getStyleId << endl;
cout << "Style Name:\t" << ptrAsa->getStyleName << endl;
ptrAsa++;
}
system("PAUSE");
return EXIT_SUCCESS;
}
My question is why do I get the error:
"a pointer to a bound function may only be used to call the function"
on both ptrAsa->getStyleId and ptrAsa->getStyleName?
I cannot figure out what is wrong with this!
You are missing () around the function calls. It should be ptrAsa->getStyleId().
You are missing parenthesis on both calls, it should be
ptrAsa->getStyleId()
to call the function.
ptrAsa->getStyleId
is used to refer to a member value / attribute.
You need to invoke the function, not merely reference it:
std::cout << "Style Id:\t" << ptrAsa->getStyleId() << "\n";
std::cout << "Style Name:\t" << ptrAsa->getStyleName() << "\n";
You are Forgot to put () in last in Your Function(ptrAsa->getStyleId ) Calling with arrow operator.