I haven't used the STL much before, but I started to on this huffman compression project. Everything seems to work except the "for_each" function, which wont except a function argument. Since I don't normally use xcode (I usually use eclipse cdt) I'm not sure if the problem is with my code or with xcode.
This is the Huff.h file
class Huff {
private:
typedef pair<char, int> c_pair;
vector<Node> nodes;
vector<Code> code;
string content;
void copy_to(c_pair c);
public:
Huff(string);
~Huff();
string compress();
bool set_content();
string get_content();
string get_compress();
};
And this is the part of the Huff.cpp file that will not work.
//---Compress---
void Huff::copy_to(c_pair c){
Node n(c.second, c.first, NULL, NULL);
nodes.push_back(n);
}
string Huff::compress(){
map<char, int> freq;
for(int i = 0; i < content.length(); i++)
freq[content[i]]++;
for_each(freq.begin(), freq.end(), copy_to); //I've also tried this->copy_to
return "110";
}
for_each(freq.begin(), freq.end(), copy_to); //I've also tried this->copy_to
copy_to is a member function which cannot be passed to std::for_each.
What you need is a callable entity which doesn't need implicit this : such an entity can be either functor or free function, and in C++11, lambda also.
The lambda solution would be pretty simple if you can use it:
for_each(freq.begin(),
freq.end(),
[this](c_pair & c) { this->copy_to(c); } );
Learn about lambda expression here:
What is a lambda expression in C++11?
As pointed out, you can't use a member function that way with for_each.
The C++03 alternative is to use mem_fun and bind1st to build a function object:
std::for_each(freq.begin(), freq.end(),
std::bind1st(std::mem_fun(&Huff::copy_to), this));
Or using Boost.Bind:
std::for_each(freq.begin(), freq.end(),
boost::bind(&Huff::copy_to, this, _1));
Related
I want to implement an unordered_map<string, string> that ignores case in the keys. My code looks like:
std::unordered_map<std::string, std::string> noCaseMap()
{
struct hasher {
std::size_t operator()(const std::string& key) const {
return std::hash<std::string>{}(toLower(key));
}
};
std::unordered_map<std::string, std::string, hasher> ret;
return ret;
}
but XCode flags the return statement with this error:
foo.cpp:181:20 No viable conversion from returned value of type 'unordered_map<[2 * ...], hasher>' to function return type 'unordered_map<[2 * ...], (default) std::hash<std::string>>'
I tried casting ret to <std::unordered_map<std::string, std::string>>, but XCode wasn't having it.
I tried making my hasher a subclass of std::hash<std::string> but that made no difference.
Edit: this is a slight oversimplification of the problem; I know I also have to implement a case-insensitive equal_to() functor as well.
You can't. There's a reason it's part of the type: efficiency. What you can do is e.g. store everything lowercase. If you need both lowercase and case-preserving, you might need two maps; but, at this point, I'd consider requesting an interface change.
I have a Mysql table that I am using as a list of different calculations that needs to be done.
Each line in the table has a column of type INT that has the number of the function that needs to be called.
e.g. line 6, data, (function) 1.
I read all the lines one by one and I need to call the relevant functions for each line.
What is the best way to construct it in C++?
should I have another function that returns the pointer of the functions that needs to be called ?
Are there other recommended solutions?
Thanks
It depends on the type of the function (input/outputs) but assuming they are all the same, you can make an array of function pointers. For example:
std::vector<void(*)(int)> MyArray;
Will declare an array of function pointers returning void and taking one int as parameter. Then you can put the functions you want in it and when you want to call them you can use MyArray[i]
If the actual type for the function pointer is long and hard to type, you can use decltype(MyFunction) instead. This requires C++11 though.
Using function pointers may work may work but I would rather make use of something like Strategy pattern.
class DataProcessor {
public:
virtual void process(Data& data) = 0;
// some other things like dtors etc
}
For each type of "function" you can create its corresponding DataProcessor.
To ease lookup, you may make use of a factory, or simply a std::map<int, DataProcessor> (instead of using int as key, will you consider using an enum?), or even a vector/array of DataProcessor.
As a suggestion, this is another way:
//Create only a function and make a switch statement in it:
void myfunction (std::pair<int,int> aRow) { // function:
int result;
int data = aRow.second;
int function_id = aRow.second;
switch(function_id){
case 1:{
//Funcion with any signature
break;
}
case 2:{
//Funcion with another signature
break;
}
//and so on...
}
//do something with the result...
}
int main () {
//Fetch your mysql data here:
std::vector<std::pair<int, int> > myMySQLdata;
for_each (myMySQLdata.begin(), myMySQLdata.end(), myfunction);
}
How can I use QtConcurrent::mapped with a member function as operator? Currently I'm using a callable object (which is ugly solution):
struct Vectorizer {
Vectorizer(DialogCreateSamples* cs)
: m_createSamples(cs) { }
typedef QString result_type;
QString operator()(const QString &input)
{
return m_createSamples->generateVector(input);
}
DialogCreateSamples* m_createSamples;
};
QFuture<QString> future = QtConcurrent::mapped(m_inputs,Vectorizer(this));
Also tried to pass lambda expressions but compiler says there is no result_type defined in lambda. This works with QtConcurrent::map because map do not need result_type. So if I can add a typedef in lambda it should work...
Maybe bind? Either std::bind if you're using C++11 or std::tr1::bind or boost::bind otherwise.
Something like:
QtConcurrent::mapped(m_inputs, std::bind(&Class::member_function, pointerToObjectOfTypeClass /* this? */, _1 /* placeholder for argument of your function filled by data from m_inputs */));
We use this in our code; example at: https://github.com/clementine-player/Clementine/blob/d03c1aa2419a0ceefd7f65114c1ac8991790b716/src/playlist/playlistbackend.cpp#L187
Hope it helps.
I can't seem to find any relevant information on the following sort of thing.
Say that you have a program with numerous methods (for example, a custom set of tests).
How could you loop through them based on something like the following pseudo-code
for(int i= 0; i < 10 ; i ++)
{
function(i)();
}
so that it will go through this loop and therefore launch methods function0, function1, function2, function3, function4, function5, function6, function7, functuin8, function9.
If there are ways to also do this in C# or Java, then information for them also would be appreciated.
In C++, the only way I can think of is to use of an array of function pointers. See here.
For Java, which supports Reflection, see this. And for C#, which also supports Reflection, this.
The language feature you would need for this is called "Reflection", which is a feature C++ does not have. You will need to explicitly name the functions you want to call.
Well, if you have an array of function pointers, you can do something like this:
void (*myStuff[256])(void);
And then when you want to call each function just dereference each of them as you iterate.
Keep in mind that every function in your array must have the same parameter signature and return type.
Here's a solution using Boost.Function and Boost.Bind in which the loop doesn't need to worry about the parameter signatures of the functions you are calling (I haven't tested it in a compiler, but I have very similar code in a project which I know works):
#include <vector>
#include <boost/function.hpp>
#include <boost/bind.hpp>
using std::vector;
using boost::function;
using boost::bind;
void foo (int a);
void bar (double a);
void baz (int a, double b);
int main()
{
// Transform the functions so that they all have the same signature,
// (with pre-determined arguments), and add them to a vector:
vector<function<void()>> myFunctions;
myFunctions.push_back(bind(&foo, 1));
myFunctions.push_back(bind(&bar, 2.0));
myFunctions.push_back(bind(&baz, 1, 2.0));
// Call the functions in a loop:
vector<function<void()>>::iterator it = myFunctions.begin();
while (it != myFunctions.end())
{
(*it)();
it++;
}
return 0;
}
Note that you can do the loop much easier if your compiler supports C++11:
// Call the functions in a loop:
for (const auto& f : myFunctions)
{
f();
}
Boost.Bind also supports passing in certain parameters dynamically instead of binding them to pre-determined values. See the documentation for more details. You could also trivially alter the above code to support return values (if they are of the same type), by replacing void with the return type, and altering the loop to do something with the returned value.
I'm confused about the for each loop in C++. I have this code in a main game loop:
for each (Bubble b in bubbles){
b.Update();
}
for each (Bubble b in bubbles){
b.Draw();
}
It doesn't update anything, but does draw 1 bubble.. What's wrong with it?
EDIT: This code works
struct BubbleUpdater {
void operator()(Bubble & b) { b.Update(); }
} updater;
struct BubbleDrawer {
void operator()(Bubble & b) { b.Draw(); }
} drawer;
void OnTimer(){ //this is my main game loop
std::for_each(bubbles.begin(),bubbles.end(),drawer);
std::for_each(bubbles.begin(),bubbles.end(),updater);
}
I had this problem as well in C#, it drove me crazy for a while. From what I found, the for each loop creates a new object for each object in your collection. So it's creating something by value, rather than by reference (if you used a standard for loop), which results in the original collection not being effected. I always found for each loops good for reading, but not for updating.
Change your BubbleUpdater class to accept it's argument by reference
struct BubbleUpdater {
void operator()(Bubble & b) { b.Update(); }
} updater;
With that, your call to std::for_each should work.
If your compiler supports it (and VC10 does), then you can use lambdas instead of creating a distant function object class. And yes, it's standard c++, or will be soon enough.
std::for_each (bubbles.begin(), bubbles.end(), [](Bubble & b){
b.Update();
});
That's not C++, it's a Qt extension from memory. The new C++0x for each loop will have the syntax
for(type identifier : expression)
that is,
for(auto x : std::string("ohai"))
However, in C++03 there is no dedicated for each loop language construct.
for each isn't valid c++, and if you were thinking of std::for_each() or BOOST_FOREACH they have different syntax.
std::for_each is a function and has the following interface:
std::for_each(InputIterator begin, InputIterator end, function f);
BOOST_FOREACH is a preprocessor macro and has the following interface:
BOOST_FOREACH(element e, container c)
{
do_thing(e);
e.whatever();
}