The method below is keeping track of how many times specific numbers come up from groupings of various sets of numbers
void build_prob_distro(const std::vector<Foo>& num_sets, std::map<int, int>& prob_distro){
int key;
Foo cur_foo;
for(unsigned int foo_num = 0; foo_num<num_sets.size(); foo_num++){
cur_foo = num_sets.at(foo_num);
key = 0;
int val;
for(int cur_foo_num=0; cur_foo_num<cur_foo.get_foo_length(); cur_foo_num++){
std::cout << cur_foo.get_num_at(cur_foo_num)*std::pow(10, cur_foo.get_foo_length()-cur_foo_num-1) << std::endl;
val = cur_foo.get_num_at(cur_foo_num)*std::pow(10, cur_foo.get_foo_length()-cur_foo_num-1);
std::cout << val << std::endl;
key = key + cur_foo.get_num_at(cur_foo_num)*std::pow(10, cur_foo.get_foo_length()-cur_foo_num-1);
}
prob_distro[key] += 1;
}
}
The problem I am running into is when I use the std::pow() method to calculate the key value for my map, anything over 100 is off by -1 (i.e. 100 becomes 99, 103 becomes 102, etc.). When I print out the calculation with std::cout the result is correct, but as soon as I assign the value to an int variable it get the -1 error. I have looked the code over and over and do not see anything immediately wrong with it. Any suggestions on what may cause this issue and why?
I don't believe the foo class is too important to this example/issue, but I will post it just in-case it actually is the cause of some issue.
//Foo.h
#ifndef FOO_H
#define FOO_H
#include <string>
#include <vector>
class Foo
{
public:
Foo();
Foo(const std::vector<int>& nums);
int get_num_at(int pos) const;
int get_foo_length() const;
std::string to_string() const;
private:
std::vector<int> nums;
};
#endif // Foo_H
//Foo.cpp
#include "Foo.h"
#include <string>
Foo::Foo(const std::vector<int>& nums){
for(int i=0; i<nums.size(); i++){
this->nums.push_back(nums.at(i));
}
}
Foo::Foo(){}
/* SETTERS & GETTERS */
int Foo::get_num_at(int pos) const{
if(nums.size() != 0){
return nums[pos];
}
return -1;
}
int Foo::get_foo_length() const{
return nums.size();
}
/* END SETTERS & GETTERS */
std::string Foo::to_string() const{}
EDIT: I know some will immediately point to using something easier than the Foo class in a vector, but I have other functionality that I need incorperated with each set, so this was the best way I could come up with to keep my related code together and allow it to represent any length integer value I would be interested in (i.e. foo can represent 1 just as easily as it can represent 10000).
You're probably getting rounding errors,
so, you may try
std::lround
as:or write your own
pow_int
function to avoid to usefloat
:or (linear version)