Gary said:
many thanks, here is the code after all the repairs
Various comments follow:
**************** statistics.h ****************
#ifndef STATISTICS_H
#define STATISTICS_H
#include <vector>
using std::vector;
#include <map>
using std::map;
class statistics
{
map<char, int> mp;
vector<char> v;
void stock_take();
public:
statistics(vector<char> const& cv);
~statistics(){}
map<char,int> get_counts();
};
#endif
**************** statistics.cpp ****************
#include <vector>
using std::vector;
#include <algorithm>
using std::max;
#include "statistics.h"
statistics::statistics(vector<char> const& cv)
: v( cv )
{
stock_take();
}
void statistics::stock_take()
{
char r = 'r';
char c = 'c';
It seems a bit silly to define a variable named x for the character 'x'.
Why not just use the character name directly?
int current_count = 0;
int best_count = 0;
for (vector<char>::const_iterator it = v.begin(); it != v.end(); ++it)
if (*it == r)
best_count = max(best_count,++current_count);
else
if (*it != r){
There no need for the second if clause. If you make it to the else
clause then it must be that (*it == 'r') was false so the second if
clause, if reached, is *always* true.
current_count = 0;
if (*it == c)
mp[c]++ ;
}
I assume you realize that this treats 'r' and 'c' differently. It
counts the longest consecutive sequence of 'r' but counts simply the
total number of 'c'.
mp[r] = best_count;
}
map<char,int> statistics::get_counts(){
return mp;
}
**************** statistics_test.cpp ****************
#include <iostream>
using std::cout;
#include <vector>
using std::vector;
#include <map>
using std::map;
#include "statistics.h"
int main() {
vector<char> v;
v.push_back('c');
v.push_back('r');
v.push_back('r');
v.push_back('c');
v.push_back('r');
v.push_back('r');
v.push_back('r');
v.push_back('r');
There are easier ways to populate a vector, for example:
std::string s( "crrcrrrr" );
std::vector<char> v( s.begin(), s.end() );
Or you could even change your code to work with strings instead of
vectors. It would be a trivial change since all you do with a vector is
iterate over its characters and that can be done identically with a string.
statistics st1(v);
map<char, int> mci = st1.get_counts();
cout << "c" << mci['c']
<< "r" << mci['r']
<< '\n';
}
**************** output ****************
c2r4