Can't get std::map to insert from function - function

I am trying to add items to a map that is a private variable in a class based on if certain parameters are met. When I try to use the insert function for std::map or the [] operator, nothing happens. I don't even get an error. During debugging the code executes like everything is fine but the map stays empty.
I have tried multiple ways to insert to the map including the [] operator and different insert arguments.
class foo {
private:
std::map<std::string, int> map;
public:
void bar();
};
In cpp file:
void foo::bar() {
if(condition)
map.insert(std::make_pair("string", 1));
}
There are no error messages or warnings in the compiler or during debugging.

If the basic STD map usage works, maybe the problem sits in your condition implementation
#include <iostream>
#include <map>
class Foo {
std::map<std::string, int> map;
public:
void bar();
void print();
};
void Foo::bar() {
// if (condition) // weird condition causing failure
map.insert(std::make_pair("string", 1));
}
void Foo::print() {
std::cout << map.size() << std::endl;
std::cout << map.at("string") << std::endl;
}
int main(void) {
Foo foo;
foo.bar();
foo.print();
}

Related

Dynamic function call through member function via map and arguments unpacking through template

I have tried code written on some link provided for dynamic function call , but unable to run code on machine .I tried to run code present at stackoverflow.com/questions/15764078/dynamically-creating-a-c-function-argument-list-at-runtime through member function.
It is is giving bad call exception while running :
Code snnippets
#include <iostream>
#include <functional>
#include <stdexcept>
#include <string>
#include <boost/any.hpp>
class Test;
class Test
{
public:
template <typename Ret, typename... Args>
Ret callfunc (std::function<Ret(Args...)> func, std::vector<boost::any> anyargs);
template <typename Ret>
Ret callfunc (std::function<Ret()> func, std::vector<boost::any> anyargs)
{
if (anyargs.size() > 0)
throw std::runtime_error("oops, argument list too long");
return func();
}
template <typename Ret, typename Arg0, typename... Args>
Ret callfunc (std::function<Ret(Arg0, Args...)> func, std::vector<boost::any>anyargs){
if (anyargs.size() == 0)
throw std::runtime_error("oops, argument list too short");
Arg0 arg0 = boost::any_cast<Arg0>(anyargs[0]);
anyargs.erase(anyargs.begin());
std::function<Ret(Args... args)> lambda =
([=](Args... args) -> Ret {
return func(arg0, args...);
});
return callfunc (lambda, anyargs);
}
template <typename Ret, typename... Args>
std::function<boost::any(std::vector<boost::any>)> adaptfunc (Ret (Test::*func)(Args...)) {
std::function<Ret(Test*,Args...)> stdfunc = func;
std::function<boost::any(std::vector<boost::any>)> result =
([=](std::vector<boost::any> anyargs) -> boost::any {
return boost::any(callfunc(stdfunc, anyargs));
});
return result;
}
int func1 (int a)
{
std::cout << "func1(" << a << ") = ";
return 33;
}
};
int main ()
{
Test a;
std::vector<std::function<boost::any(std::vector<boost::any>)>> fcs =
{
a.adaptfunc(&Test::func1)};
std::vector<std::vector<boost::any>> args =
{{777}};
// correct calls will succeed
for (int i = 0; i < fcs.size(); ++i)
std::cout << boost::any_cast<int>(fcs[i](args[i])) << std::endl;
return 0;
}
This code compiled successfully
But it failed to run and crashed
In main function for loop.
Function needs typecast according to their signature e.g.:
a.adaptfunc((int(*)(int))&Test::func1)};
After this typecast function call will not fail

C++ Linked List Deep Copy Constructor and Assignment Overloaded

#ifndef LIST
#define LIST
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
typedef string ElementType;
class List
{
private:
class Node
{
public:
ElementType data;
Node * next;
Node()
:data(ElementType()), next(NULL)
{}
Node(ElementType initData)
:data(initData), next(NULL)
{}
}; // end of Node class
typedef Node * NodePointer;
public:
private:
NodePointer first;
int mySize;
}; // end of List class
This is my overloaded assignment operator, im not sure what im doing wrong, but im beyond frustrated,I've searched the web and read different forums and cannot find a solution to do this, could someone please push me in the right direction, I left out all my public member functions, because none of them operate on my overloaded assignment and copy constructor, I just wanted you guys to get an idea of my layout
overloaded assignment operator
List & List::operator=(const List &rightSide)
{
if(this != &rightSide)
{
this->~List();
}
NodePointer ptr = rightSide.first;
NodePointer cptr = ptr;
while(ptr != NULL)
{
cptr->next = new Node(ptr->data);
cptr = cptr->next;
ptr = ptr->next;
}
return *this;
}
this is my copy constructor
List::List(const List &source)
{
NodePointer ptr = source.first;
NodePointer cptr;
if(ptr == NULL)
{
cerr << "Bad allocation, empty list" << endl;
exit(1);
}
while(ptr != NULL)
{
cptr = new Node(ptr->data);
cptr->next = ptr->next;
ptr = ptr->next;
}
}

Use std::bind to bind to the parent's version of a virtual function

I want to create a std::function object for the parent class's version of a virtual and overridden function, see the following example:
#include <iostream>
#include <functional>
class Parent
{
public:
virtual void func1()
{
std::cout << "Parent::func1\n";
}
virtual void func2()
{
std::cout << "Parent::func2\n";
}
};
class Child : public Parent
{
public:
// overrides Parent::func1
virtual void func1()
{
std::cout << "Child::func1, ";
Parent::func1();
}
// overrides Parent::func2
virtual void func2()
{
std::cout << "Child::func2, ";
std::function< void() > parent_func2 = std::bind( &Parent::func2, this );
parent_func2();
}
};
int main()
{
Child child;
child.func1(); // output: Child::func1, Parent::func1
child.func2(); // output: Child::func2, Child::func2, ...
return 0;
}
While the call to child.func1() behaves as expected, the call to child.func2() becomes an infinite recursion, where parent_func2() seems to call Child::func2() instead of Parent::func2() to which I intended to bind it.
Any idea how I can have parent_func2() really call Parent::func2?
You can do it by writing a small functor:
struct Parent_func2
{
void operator()( Parent* p ) const
{
p->Parent::func2();
}
};
And use
std::function< void() > parent_func2 = std::bind( Parent_func2(), this );
(thinking about it, I guess this is just a more verbose way of what Xeo suggested. #Xeo, make your comment an answer and you have my upvote...)

Different memory address in C++ constructors

I have two constructors in C++, and one constructor calls the other one in order not to duplicate initialization logic.
#include <iostream>
#include <memory>
using namespace std;
class A
{
int x;
int y;
public:
A(int x)
{
cout << this << endl;
this->x = x;
}
A()
{
cout << this << endl;
A(20);
}
...
};
What is interesting is A() calls A(int), but the this pointer points to different address. Why is this? Or is this g++ bug?
int main(int argc, char *argv[]) {
A* a = new A();
}
0x7fa8dbc009d0 <-- from A()
0x7fff67d660d0 <-- from A(int)
I believe A(20); is constructing a different instance of A within that constructor, not invoking the other constructor on the same instance.
See Can I call a constructor from another constructor (do constructor chaining) in C++? for how to invoke another constructor from a constructor.
If you are using a compiler that supports C++11, I think you can achieve what you want with this definition of the A() constructor:
A(): A(20)
{
cout << this << endl;
}
A(20); is a statement which constructs a new instance of A, not a call to A's constructor on this.
You can't call another constructor overload inside a given constructor in C++03. However, you can achieve the same effect by using placement new. Replace:
A(20);
in your code with:
new (this) A(20);

Functions in struct in c only

I am having a hard time compiling this C code.
Basically what happens is:
it does compile but when I run it (on Terminal) it prints me:Illegal instruction
I tried to debug it and on Xcode and when it attempts to execute (*fraction).print() it says: EXC_BAD_ACCESS
if I delete the (*fraction).print() line everything works fine (same happens if I only delete the next line)
GNU99 and -fnested-functions flag is enabled
I do not want to change the main function just the other stuff
This code drove me crazy for a whole afternoon so a little help would be really appreciated.
Thankyou
#include <stdlib.h>
#include "string.h"
#include "stdio.h"
typedef struct
{
int numerator;
int denominator;
void (*print)(); // prints on screen "numerator/denominator"
float (*convertToNum)(); //returns value of numerator/denominator
void (*setNumerator)(int n);
void (*setDenominator)(int d);
} Fraction;
Fraction* allocFraction(Fraction* fraction); //creates an uninitialized fraction
void deleteFraction(Fraction *fraction);
Fraction* allocFraction(Fraction* fraction)
{
void print()
{
int a= 10;
printf("%i/%i", (*fraction).numerator, (*fraction).denominator);
a--;
}
float convertToNum()
{
return (float)(*fraction).numerator/(float)(*fraction).denominator;
}
void setNumerator (int n)
{
(*fraction).numerator= n;
}
void setDenominator (int d)
{
(*fraction).denominator= d;
}
if(fraction== NULL)
fraction= (Fraction*) malloc(sizeof(Fraction));
if(fraction)
{
(*fraction).convertToNum= convertToNum;
(*fraction).print= print;
(*fraction).setNumerator= setNumerator;
(*fraction).setDenominator= setDenominator;
}
return fraction;
}
void deleteFraction(Fraction *fraction)
{
free(fraction);
}
int main (int argc, const char * argv[])
{
Fraction *fraction= allocFraction(fraction);
(*fraction).setNumerator(4);
(*fraction).setDenominator(7);
(*fraction).print(); //EXC_BAD_ACCESS on debug. Illegal instruction in Terminal
printf("%f", (*fraction).convertToNum());
(*fraction).print();
deleteFraction(fraction);
return 0;
}
You can't write C in the same way you write Javascript.
Specifically, it appears that print() is a nested function inside allocFraction() (which is itself not standard C but a gcc extension). You can't call a nested function through a function pointer from outside the scope of where it's defined. This is true even if you don't access anything in the outer scope from the nested scope.
Your code appears to be attempting to do object-oriented programming in C. Have you considered C++?