A program using class template, pair, vector - class

I'm trying to program the following:
A template class map having a pointer to a vector that contains elements std::pair<T,Q>, where T and Q are template types. It's supposed to work similarly to std::map and T is 'key' type, whereas Q stands for 'value' type. Besides the following should be implemented:
1. Constructor & destructor.
2. Function empty returning bool (if the object is empty).
3. Function size (using count_if)
4. Function clear that deletes all vector records.
5. Operator [] which allows for: map["PI_value"] = 3.14; It should use function find
6. Operators =, ==, !=, >> (using equal function)
I've been trying to code the above task, but have stuck on the code below.
Do you have any ideas to repair this mess?
#include <iostream>
#include <tuple>
#include <utility>
#include <algorithm>
#include <vector>
using namespace std;
template <typename T, typename Q>
class mapa
{
private:
vector<std::pair<T,Q>>* ptr;
public:
/**< DEFAULT CONSTRUCTOR/////////////////////////// */
mapa()
{
ptr = new vector<std::pair<T,Q>>;
ptr->push_back(std::pair<T,Q>(0,0));
}
/**< DESTRUCTOR////////////////////////////////////// */
~mapa(){ delete ptr;}
/**< EMPTY()////////////////////////////// */
bool empty()
{
if(ptr)
return false;
else
return true;
}
/**< SIZE()///////////////////////////////// */
int size()
{
return ptr->size();
}
/**< CLEAR()///////////////////////////////// */
void clear()
{
ptr->clear(ptr->begin(), ptr->end());
}
/**< OPERATOR[]/////////////////////////////////////////// */
vector<std::pair<T,Q>>* & operator[](T key)
{
auto ptr2 = ptr;
if(empty())
{
std::pair<T,Q> para;
para.first = key;
para.second = 0;
ptr2->push_back(para);
//ptr2->push_back(std::pair<T,Q>(key,0));
}
else
{
auto ptr2 = find_if( ptr->begin(), ptr->end(),
[](std::pair<T,Q> example,T key)
{
return(example.first==key);
}
);
}
return ptr2;
}
}; //class end

The lambda provided to std::find_if is declared wrong.
If you see e.g. this reference for std::find_if, you will see that the functions should be like
bool pred(const Type &a)
That means the lambda should be something like
[&key](const std:pair<T, Q>& element) { return element.first == key }
There are also other problems with your operator[] function, like that it should return Q& instead of a reference to the vector pointer. You should also remember that std::find_if returns an iterator to the found element, or end() if not found.

Related

what is the correct syntax function pointer list with class member?

I have a list of function pointers, the non-class member compiles without errors, but the class member compiles with errors:
error: cannot convert 'void (CVdmConfig::)()' to 'fp {aka void ()()}' in initialization
CVdmConfig::writeConfig is a void function.
typedef void (*fp)();
fp fpList[] = {&valvesCalib,&CVdmConfig::writeConfig} ;
What do I wrong ?
best regards
Werner
Without seeing the rest of your code, there is not much I can debug, but here is an example that works:
#include <iostream>
using namespace std;
void valvesCalib() {
cout << "inside function\n";
}
class CVdmConfig {
public:
static void writeConfig() {
cout << "inside method\n";
}
};
typedef void (*fp)();
fp fpList[] = {
&valvesCalib,
&CVdmConfig::writeConfig
};
int main()
{
for (auto f: fpList) {
f();
}
return 0;
}
/*
Output:
inside function
inside method
Program finished with exit code 0
*/
The problem was the missing static definition in the member function. But this leads into other problems with variables in the class. So I use a wrapper for this.

Compile Errors in Class with User Defined Functions

I am trying to build a class that stores a user-defined function inside of it for later use. I have decided to use the boost::function object to do so.
However, I get the following error on compile:
error: no match for ‘operator=’ in ‘((SomeClass*)this)->SomeClass::someFunction = ((SomeClass*)this)->SomeClass::DefaultFunction’
I do not understand this error, since someFunction and DefaultFunction should, as far as I can see, have the same types.
The code is shown below:
#include <boost/function.hpp>
class SomeClass{
private:
boost::function<int(int)> someFunction;
int DefaultFunction(int i);
public:
SomeClass();
~SomeClass();
void SetFunction(int (*f)(int));
};
int SomeClass::DefaultFunction(int i){
return i+1;
}
SomeClass::SomeClass(){
someFunction=DefaultFunction;
}
~SomeClass::SomeClass(){
}
void SomeClass::SetFunction(int (*f)(int i)){
someFunction=f;
}
void MyProgram(){
SomeClass s;
}
Can anyone offer any pointers as to how to construct such an object? Alternatively, iff there is a better way than the one I am attempting, could you explain it to me?
Kindest regards!
DefaultFunction is a member function of SomeClass.
Member function is called for some instance of SomeClass.
This function takes "hidden" pointer to SomeClass instance as its first parameter addition to int.
So member function is not the same as free function.
Your someFunction is object of boost::function, so it is wrapper for callable object.
Your requirements to that object are: take int and returns int.
In order to assign DefaultFunction (as member function) to someFunction you need to create this callable object.
Here you need to specify for which instance of SomeClass this object will be called, to do that use boost::bind:
SomeClass::SomeClass(){
someFunction=boost::bind(&SomeClass::DefaultFunction, this, boost::placeholders::_1);
}
In the code above you create callable object which will behave as
struct unnamedClass {
SomeClass* sc;
unnamedClass (SomeClass* sc) : sc(sc) {} // here sc is this of SomeClass
int operator()(int arg)
{
return sc->DefaultFunction(arg);
}
};
so when you invoke someFunction(10) it takes 10 as argument and call DefaultFunction for current this instance.
This
void SomeClass::SetFunction(int (*f)(int i)){
someFunction=f;
}
works because f is free function, which takes no hidden - pointer to class instance.
Using the answer of #rafix07, the following code compiled:
#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/bind/placeholders.hpp>
class SomeClass{
private:
public:
SomeClass();
~SomeClass();
boost::function<int(int)> someFunction;
int DefaultFunction(int i);
void SetFunction(int (*f)(int));
};
int SomeClass::DefaultFunction(int i){
return i+1;
}
SomeClass::SomeClass(){
someFunction=boost::bind(&SomeClass::DefaultFunction, this, _1);
}
SomeClass::~SomeClass(){
}
void SomeClass::SetFunction(int (*f)(int i)){
someFunction=f;
}
int MyOwnProgram(int i){
return i+2;
}
void MyProgram(){
SomeClass s;
std::cout<<s.someFunction(2)<<std::endl;
s.SetFunction(MyOwnProgram);
std::cout<<s.someFunction(2)<<std::endl;
}
int main()
{
MyProgram();
}
The output from the program is:
3
4

How to use references and pointers in c++ classes?

i have the following problem: I am using an existing class which creates an object called server_t.
Another function expects *server_t as an argument.
I wanted to shrink the code and added a class which has following members:
#ifndef _PMCLASS
#define _PMCLASS
#include "pmlib.h"
class pmServer{
private:
server_t server ;
counter_t counter;
line_t lines;
server_t * server2;
int set, frequency, aggregate ;
public:
pmServer();
pmServer(int set, int frequency, int aggregate);
~pmServer();
void setSet(int s);
void setFrequency(int f);
void setAggregate(int a);
int getSet(void);
int getFrequency(void);
int getAggregate(void);
server_t* getServerT(void);
counter_t* getCounterT(void);
line_t* getLineT(void);
server_t* getZeiger(void);
};
#endif
then i created the constructors:
#include "pmClass.h"
#include <iostream>
using namespace std;
void pmServer::setSet(int s){
this->set = s;
}
void pmServer::setFrequency(int f){
this->frequency = f;
}
void pmServer::setAggregate(int a){
this->aggregate = a;
}
int pmServer::getSet(void){
return set;
}
int pmServer::getFrequency(void){
return frequency;
}
int pmServer::getAggregate(void){
return aggregate;
}
server_t* pmServer::getPointer(){
return &server;
}
pmServer::pmServer(){
set = -1;
frequency = 0;
aggregate = 1;
}
then i tried to create an object ->worked, but then i wanted to use the pm_set_server(...)
it wants following arguments: int pm_set_server( char *ip, int port, server_t *pm_server)
void run() {
build_initial_mesh();
// Construct / read in the initial mesh.
pmServer server1;
pm_set_server("xxx.xxx.xxx.xxx", 6526,server1.getPointer); //its a correct ip address , no panic :)
i got that:
error: argument of type 'server_t*' (pmServer::)() does not match 'server_t*'
but this worked without any problems:
void run() {
// Construct / read in the initial mesh.
//pmServer server1;
server_t test;
pm_set_server("xxx.xxx.xxx.xxx", 6526,&test);
build_initial_mesh();
The thing is, i didn't want to create everytime new ojects and wanted to do that in the constructor...Does somebody have any idea?
thanks.
greetings Thomas
In C++, function calls need brackets*:
pm_set_server("xxx.xxx.xxx.xxx", 6526,server1.getPointer());
*exceptions apply, for operators.

Visual C++ not know function return value which is a user defined class

I have,
time.h:
#pragma once
#ifndef TIME_H
#define TIME_H
class time
{
private:
int hour;
int minute;
int second;
public:
enum pmORam {am,pm};
time(void);
time(int,int,int);
void printtime(void);
time subtime(time &);
const time &operator=(const time &);
void setTime(int,int,int);
~time(void);
};
#endif
time.cpp:
#include <iostream>
#include <iomanip>
#include "stdafx.h"
#include "time.h"
using namespace std;
time::time(void)
{
hour=0;
minute=0;
second=0;
}
time::time(int hr,int min,int sec)
{
setTime(hr,min,sec);
}
void time::printtime(void)
{
enum pmORam p;
if(hour<=12 && hour>=0)
cout<<setfill('0')<<setw(2)<<hour<<":"<<setw(2)<<minute<<":"<<setw(2)<<second<<p.am<<endl;
else
if(hour>12 && hour<=23)
{
hour=hour%12;
cout<<setfill('0')<<setw(2)<<hour<<":"<<setw(2)<<minute<<":"<<setw(2)<<second<<p.pm<<endl;
}
}
const time &time::operator=(const time &t)
{
hour=t.hour;
minute=t.minute;
second=t.second;
return *this;
}
time time::subtime(time &m)
{
if(hour>m.hour)
{
if(m.second>second)
{
minute=minute-1;
second=(second+60)-m.second;
}
second=second-m.second;
if(m.minute>minute)
{
hour=hour-1;
minute=(minute+60)-m.minute;
}
minute=minute-m.minute;
hour=hour-m.hour;
}
if(second>m.second)
{
m. minute=m.minute-1;
m.second=(m.second+60)-second;
}
m.second=m.second-second;
if(minute>m.minute)
{
m.hour=m.hour-1;
m.minute=(m.minute+60)-minute;
}
m.hour=hour-m.hour;
return *this;
}
void time::setTime(int hr,int min,int sec)
{
hour=(hr>=0 && hr<=23)? hr: 0;
minute=(min>=0 && min<60)? min:0;
second=(sec>=0 && sec<60)? sec:0;
}
time::~time(void)
{
}
But in time.cpp i get to this Errors:
IntelliSense: declaration is incompatible with "time time::subtime(time &)"
IntelliSense: declaration is incompatible with "const time &time::operator=(const time &)"
'time::time(const time &)' : cannot convert parameter 1 from 'time *const ' to 'const time &'
'int time::subtime(time &)' : overloaded function differs only by return type from 'time time::subtime(time &)'
'int &time::operator =(const time &)' : overloaded function differs only by return type from 'const time &time::operator =(const time &)'
function "time" is not a type name
What is Problem?
Edit: New code to fix naming conflict
time.cpp:
#include <iostream>
#include <iomanip>
#include "stdafx.h"
#include "time.h"
using namespace std;
timea::timea(void)
{
hour=0;
minute=0;
second=0;
}
timea::timea(int hr,int min,int sec)
{
setTime(hr,min,sec);
}
void timea::printtime(void)
{
enum timea::pmORam p;
if(hour<=12 && hour>=0)
cout<<setfill('0')<<setw(2)<<hour<<":"<<setw(2)<<minute<<":"<<setw(2)<<second<<p.am<<endl;
else
if(hour>12 && hour<=23)
{
hour=hour%12;
cout<<setfill('0')<<setw(2)<<hour<<":"<<setw(2)<<minute<<":"<<setw(2)<<second<<p.pm<<endl;
}
}
const timea &timea::operator=(const timea &t)
{
hour=t.hour;
minute=t.minute;
second=t.second;
return *this;
}
timea timea::subtime(timea &m)
{
if(hour>m.hour)
{
if(m.second>second)
{
minute=minute-1;
second=(second+60)-m.second;
}
second=second-m.second;
if(m.minute>minute)
{
hour=hour-1;
minute=(minute+60)-m.minute;
}
minute=minute-m.minute;
hour=hour-m.hour;
}
if(second>m.second)
{
m. minute=m.minute-1;
m.second=(m.second+60)-second;
}
m.second=m.second-second;
if(minute>m.minute)
{
m.hour=m.hour-1;
m.minute=(m.minute+60)-minute;
}
m.hour=hour-m.hour;
return *this;
}
void timea::setTime(int hr,int min,int sec)
{
hour=(hr>=0 && hr<=23)? hr: 0;
minute=(min>=0 && min<60)? min:0;
second=(sec>=0 && sec<60)? sec:0;
}
timea::~timea(void)
{
}
There's a header file in the Standard library named time.h. It's likely that either
You're including the system header file when you wanted your own, or
System header files are pulling in yours when they wanted the standard one
or both. Find a different name for your header.
In addition, the identifier time in the global namespace is used by a function in the Standard library (hence the error function "time" is not a type name). So put yours inside a namespace or change the class name.
Specifically, your errors are caused by ignoring this rule, found in 17.6.4.3.3:
Each name from the Standard C library declared with external linkage is reserved to the implementation for use as a name with extern "C" linkage, both in namespace std and in the global namespace.
Each function signature from the Standard C library declared with external linkage is reserved to the implementation for use as a function signature with both extern "C" and extern "C++" linkage, or as a name of namespace scope in the global namespace.

What are function typedefs / function-type aliases in Dart?

I have read the description, and I understand that it is a function-type alias.
A typedef, or function-type alias, gives a function type a name that you can use when declaring fields and return types. A typedef retains type information when a function type is assigned to a variable.
http://www.dartlang.org/docs/spec/latest/dart-language-specification.html#kix.yyd520hand9j
But how do I use it? Why declaring fields with a function-type? When do I use it? What problem does it solve?
I think I need one or two real code examples.
A common usage pattern of typedef in Dart is defining a callback interface. For example:
typedef void LoggerOutputFunction(String msg);
class Logger {
LoggerOutputFunction out;
Logger() {
out = print;
}
void log(String msg) {
out(msg);
}
}
void timestampLoggerOutputFunction(String msg) {
String timeStamp = new Date.now().toString();
print('${timeStamp}: $msg');
}
void main() {
Logger l = new Logger();
l.log('Hello World');
l.out = timestampLoggerOutputFunction;
l.log('Hello World');
}
Running the above sample yields the following output:
Hello World
2012-09-22 10:19:15.139: Hello World
The typedef line says that LoggerOutputFunction takes a String parameter and returns void.
timestampLoggerOutputFunction matches that definition and thus can be assigned to the out field.
Let me know if you need another example.
Dart 1.24 introduces a new typedef syntax to also support generic functions. The previous syntax is still supported.
typedef F = List<T> Function<T>(T);
For more details see https://github.com/dart-lang/sdk/blob/master/docs/language/informal/generic-function-type-alias.md
Function types can also be specified inline
void foo<T, S>(T Function(int, S) aFunction) {...}
See also https://www.dartlang.org/guides/language/language-tour#typedefs
typedef LoggerOutputFunction = void Function(String msg);
this looks much more clear than previous version
Just slightly modified answer, according to the latest typedef syntax, The example could be updated to:
typedef LoggerOutputFunction = void Function(String msg);
class Logger {
LoggerOutputFunction out;
Logger() {
out = print;
}
void log(String msg) {
out(msg);
}
}
void timestampLoggerOutputFunction(String msg) {
String timeStamp = new Date.now().toString();
print('${timeStamp}: $msg');
}
void main() {
Logger l = new Logger();
l.log('Hello World');
l.out = timestampLoggerOutputFunction;
l.log('Hello World');
}
Typedef in Dart is used to create a user-defined function (alias) for other application functions,
Syntax: typedef function_name (parameters);
With the help of a typedef, we can also assign a variable to a function.
Syntax:typedef variable_name = function_name;
After assigning the variable, if we have to invoke it then we go as:
Syntax: variable_name(parameters);
Example:
// Defining alias name
typedef MainFunction(int a, int b);
functionOne(int a, int b) {
print("This is FunctionOne");
print("$a and $b are lucky numbers !!");
}
functionTwo(int a, int b) {
print("This is FunctionTwo");
print("$a + $b is equal to ${a + b}.");
}
// Main Function
void main() {
// use alias
MainFunction number = functionOne;
number(1, 2);
number = functionTwo;
// Calling number
number(3, 4);
}
Output:
This is FunctionOne
1 and 2 are lucky numbers !!
This is FunctionTwo
3 + 4 is equal to 7
Since dart version 2.13 you can use typedef not only with functions but with every object you want.
Eg this code is now perfectly valid:
typedef IntList = List<int>;
IntList il = [1, 2, 3];
For more details see updated info:
https://dart.dev/guides/language/language-tour#typedefs
https://www.tutorialspoint.com/dart_programming/dart_programming_typedef.htm
typedef ManyOperation(int firstNo , int secondNo); //function signature
Add(int firstNo,int second){
print("Add result is ${firstNo+second}");
}
Subtract(int firstNo,int second){
print("Subtract result is ${firstNo-second}");
}
Divide(int firstNo,int second){
print("Divide result is ${firstNo/second}");
}
Calculator(int a,int b ,ManyOperation oper){
print("Inside calculator");
oper(a,b);
}
main(){
Calculator(5,5,Add);
Calculator(5,5,Subtract);
Calculator(5,5,Divide);
}