My program is written in C++.
#include <iostream>
#include <string>
#include <map>
using namespace std;
class Details
{
int x;
int y;
};
typedef std::map<string, Details> Det;
Det det;
Details::Details(int p, int c) {
x = p;
y = c;
}
int main(){
det.clear();
insertNew("test", 1, 2);
cout << det["test"] << endl;
return 0;
}
I want to print the value of a key with the simplest way. Eg det["test"] fails to compile.
How to I print values (1,2) for (x,y) that correspond to key "test"?
My best guess is that you have no default or copy constructor in your Obj (you don't have any in the code you posted, but I assume you have one that takes two integers). You've also got a typo in the catalog.insert() line. Here is what worked for me, using your code:
class Obj {
public:
Obj() {}
Obj(int x, int y) : x(x), y(y) {}
int x;
int y;
};
int main (int argc, char ** argv) {
std::map<std::string, Obj> catalog;
catalog.insert(std::map<std::string, Obj>::value_type("test", Obj(1,2)));
std::cout << catalog["test"].x << " " << catalog["test"].y << std::endl;
return 0;
}
Create an operator<< for your class Obj and then you can do something like std::cout << catalog["test"]; (I'm assuming that the missing parens in the insert call are just a copy-paste-o).
I've changed a bit your code.
#include <map>
#include <iostream>
#include <string>
using namespace std;
class Obj {
public:
Obj( int in_x, int in_y ) : x( in_x ), y( in_y )
{};
int x;
int y;
};
int main()
{
std::map< string, Obj* > catalog;
catalog[ "test" ] = new Obj(1,2);
for( std::map<string, Obj*>::iterator i=catalog.begin(); i != catalog.end(); ++i )
{
cout << "x:" << i->second->x << " y:" << i->second->y << endl;
}
}
Given these types:
class Obj {
int x;
int y; };
std::map<string, Obj> catalog;
Given a populated catalog object:
for(auto ob = catalog.begin(); ob != catalog.end(); ++ob)
{
cout << ob->first << " " << ob->second.x << " " << ob->second.y;
}
Related
#include <iostream>
#include <string.h>
#include "Date.h"
#include "Employee.h"
using std::cout;
using std::endl;
using std::to_string;
class TestOps {
public:
int sex = 1;
string toString() {
return " sex:" + to_string(sex) ;
}
};
class Test {
public:
TestOps* testOps;
Test(const Test& t) :Test{} {
this->testOps = new TestOps{ *(t.testOps) };
};
Test() {
TestOps ops;
//this->testOps = new TestOps{}; // it will be ok with this way
this->testOps = &ops;
}
};
int main() {
// code not understand
Test t1;
cout <<"first testOps:" << t1.testOps->toString() << endl; // sex: 1
Test t2{ t1 };
cout << "first testOps:" << t1.testOps->toString() << endl; // sex: -858893460 ???? why?
cout << "second testOps:" << t2.testOps->toString() << endl; // sex: -858893460 ???? why?
return 0;
}
As you can see, why the first log is as expected while the later logs are not?
Also, t1.testOps address is different from t2.testOps which is as expected.
I have done some research but didn't find the answer. Maybe because I'm pretty new to cpp.
#include <iostream>
#include <memory>
#include <initializer_list>
#include <cassert>
#include <map>
template <typename T>
class Matrix
{
private:
int i,j;
T value;
std::map<std::array<int, 2>,double> Mat;
public:
Matrix():i(0),j(0)
{
std::cout<<"Empty boi called"<<std::endl;
}
Matrix(int row, int column)
{
std::cout<<"Main boi called"<<std::endl;
}
// I'm not really sure where to plug this code in
// In the main function, this code works but not really in class
for (std::map<std::array<int, 2>,int>::iterator it=Mat.begin(); it!=Mat.end(); ++it)
{
i = it->first[0];
j = it->first[1];
value = it->second;
std::cout << "["<< it->first[0] <<","<<it->first[1]<<"]"<< " => " << it->second << '\n';
}
};
int main()
{
std::map<std::array<int, 2>,int> Mat;
Mat[{1,5}]=20;
Mat[{2,6}]=30;
for (std::map<std::array<int, 2>,int>::iterator it=Mat.begin(); it!=Mat.end(); ++it)
std::cout << "["<< it->first[0] <<","<<it->first[1]<<"]"<< " => " << it->second << '\n';
// The same code done in main function is what I want to do in the class
Matrix<double> M(10,10);
M{[1,1]} = 3.14; // This returns an error
return 0;
}
As seen, the mapping is possible when its directly in the main function, but I want to send multiple positions of M to the class and have it initialised. But completely unable to do so. Tried looking in a lot of places to no avail.
i'm new to this site, after doing some research I could not find a problem similar to mine(some questions looked like mine but their code was different)
So basically what i'm trying to do is to representing the framebuffer matrix with all different colors values. I'm coding a class named "Point", and I have one constructor, using default arguments, here it is :
Point.h
#ifndef POINT_H
#define POINT_H
#include <iostream>
class Point
{
protected:
int x;
int y;
public:
Point(int=0,int=0);
Point(const &Point);
void showC() const;
static void showC(Point);
virtual ~Point();
};
#endif // POINT_H
Point.cpp
#include "Point.h"
using namespace std;
Point::Point(int a,int b)
{
x=a;
y=b;
}
Point::~Point()
{}
void Point::showC() const
{ cout << x << " " << y << endl; }
void Point::showC(Point P)
{ cout << P.x << " " << P.y << endl; }
But the problem is when I try to compile the program
main.cpp
#include <iostream>
#include "Point.h"
using namespace std;
int main()
{
Point P1;
Point P2(2);
Point P3(4,-7);
cout << "Call of function member showC\n";
P1.showC();
P2.showC();
P3.showC();
cout << "Call of static function showC\n";
Point::showC(P1);
Point::showC(P2);
Point::showC(P3);
return 0;
}
There is an error when I create Point P2 :
"Call of overloaded 'Point(int)' is ambigous"
On all the others question i read, either it was not the same problem or they had a default constructor in addition to a constructor with default argument which cause ambiguity of which constructor to use if you create an object without argument.
On a book i'm reading to improve skills on c++, there is this sample that is working somehow, and that's why I don't really understand
Here is the sample :
main.cpp
class point
{
private :
int x;
int y;
Point (int abs=0, int ord=0) //inline constructor
{x=abs; y=ord;}
bool coincide(point);
};
bool point::coincide(point pt)
{ return ( (pt.x==x) && (pt.y==y) );
}
int main()
{
point a, b(1), c(1,0);
cout << "a and b : " << a.coincide(b) << " ou " b.coincide(a) << "\n"
cout << "b et c : " << b.coincide(c) << " ou " << c.coincide(b) << "\n"
}
However he grouped everything in the main.cpp files, and his constructor is inline.
Can anyone explain to me why is the sample working, and why my program is not ? I guess there is a mechanism that i don't understand...
Thanks in advance
RE-EDIT : I copied all the code
I think you are mixing both python and c++ way of creating class
python do use : class Point:
for declaring in class , c++ uses {} like class Point {};
Below works by changing the class declaration.
Just added a cout in your constructor
#include <iostream>
#include <vector>
using namespace std;
class Point
{
private:
int x;
int y;
public:
Point(int=0,int=0);
};
Point::Point(int a, int b)
{
x = a;
y = b;
cout<<x<<y<<endl;
}
int main()
{
Point P1;
Point P2(2);
Point P3(4,-7);
return 0;
}
Output
00
20
4-7
Program ended with exit code: 0
After question edit
Removed your buggy line and it works perfectly
Point(const &Point);
#include <iostream>
#include <vector>
using namespace std;
class Point
{
protected:
int x;
int y;
public:
Point(int=0,int=0);
//Point(const &Point);
void showC() const;
static void showC(Point);
virtual ~Point();
};
Point::Point(int a,int b)
{
x=a;
y=b;
}
Point::~Point()
{}
void Point::showC() const
{ cout << x << " " << y << endl; }
void Point::showC(Point P)
{ cout << P.x << " " << P.y << endl; }
int main()
{
Point P1;
Point P2(2);
Point P3(4,-7);
cout << "Call of function member showC\n";
P1.showC();
P2.showC();
P3.showC();
cout << "Call of static function showC\n";
Point::showC(P1);
Point::showC(P2);
Point::showC(P3);
return 0;
}
Output
Call of function member showC
0 0
2 0
4 -7
Call of static function showC
0 0
2 0
4 -7
Program ended with exit code: 0
After edit I guess you want to use copy constructor just change it to
Point(const Point &p2) {x = p2.x; y = p2.y; }
I'm attempting to use boost::static_visitor to implement actions on a boost::variant type that affect the state of some variable. My approach was to contain all of the state variables in my command visitor class, but it seems this is not possible.
Here is my code example:
#include <string>
#include <sstream>
#include <vector>
#include <boost/variant.hpp>
#include <boost/foreach.hpp>
struct TypeA
{
int varA;
int varB;
};
struct TypeB
{
std::string varA;
std::string varB;
};
typedef boost::variant<TypeA, TypeB> MyVariantType;
class MyCommandVisitor : public boost::static_visitor<>
{
public:
//These are just examples, the actions only need to be able to touch
// internal variables.
void operator()(TypeA & t) const
{
m_runningSum += t.varA;
m_outStream << "TYPEA ACTION: " << t.varB << std::endl;
}
void operator(TypeB & t) const
{
m_charCount += t.varA.size();
m_outStream << t.varB << " ACTION " << t.varA << std::endl;
}
std::string emitWork(std::vector<MyVariantType> listOfVariants)
{
m_outStream.clear();
m_runningSum = 0;
m_charCount = 0;
BOOST_FOREACH(MyVariantType & v, listOfVariants)
{
boost::apply_visitor(*this, v);
}
return m_outStream.str();
}
protected:
int m_runningSum;
int m_charCount;
std::stringstream outStream;
}; //End class MyCommandVisitor
int main(int argc, char **argv)
{
TypeA ta;
ta.varA = 1;
ta.varB = 2;
TypeB tb;
tb.varA = "String1";
tb.varB = "String2";
std::vector<MyVariantType> listOfWork;
listOfWork.push_back(ta);
listOfWork.push_back(tb);
MyCommandVisitor myCV;
std::string result = myCV.emitWork(listOfWork);
std::cout << "Result:\n" << result << std::endl << std::endl;
return 0;
}
I hope this snippet gets across the gist of what I'm trying to accomplish. It won't compile, however, giving the [paraphrased] error:
error: no operator "<<" matches these operands
operand types are: const std::stringstream << const char [N]
m_outStream << "TYPE A ACTION: " << t.varB << std::endl;
^
I'm assuming this error is due to the const modifier that must be placed on the end of the operator() function prototype which makes the compiler believe that member variables cannot be modified by the function.
My question is thus:
What is the proper way to accomplish the visitor pattern (using boost::variant) with variables that must maintain state between visits?
There were a couple of typos, but I made a few mods and it works now. Essentially your static_visitor class is mutating itself on each visit, so the operator() methods can't be const.
#include <string>
#include <sstream>
#include <vector>
#include <boost/variant.hpp>
#include <boost/foreach.hpp>
#include <iostream>
struct TypeA
{
int varA;
int varB;
};
struct TypeB
{
std::string varA;
std::string varB;
};
typedef boost::variant<TypeA, TypeB> MyVariantType;
class MyCommandVisitor : public boost::static_visitor<>
{
public:
//These are just examples, the actions only need to be able to touch
// internal variables.
void operator()(TypeA & t)
{
m_runningSum += t.varA;
m_outStream << "TYPEA ACTION: " << t.varB << std::endl;
}
void operator()(TypeB & t)
{
m_charCount += t.varA.size();
m_outStream << t.varB << " ACTION " << t.varA << std::endl;
}
std::string emitWork(std::vector<MyVariantType> listOfVariants)
{
m_outStream.clear();
m_runningSum = 0;
m_charCount = 0;
BOOST_FOREACH(MyVariantType & v, listOfVariants)
{
boost::apply_visitor(*this, v);
}
return m_outStream.str();
}
protected:
int m_runningSum;
int m_charCount;
std::stringstream m_outStream;
}; //End class MyCommandVisitor
int main(int argc, char **argv)
{
TypeA ta;
ta.varA = 1;
ta.varB = 2;
TypeB tb;
tb.varA = "String1";
tb.varB = "String2";
std::vector<MyVariantType> listOfWork;
listOfWork.push_back(ta);
listOfWork.push_back(tb);
MyCommandVisitor myCV;
std::string result = myCV.emitWork(listOfWork);
std::cout << "Result:\n" << result << std::endl << std::endl;
return 0;
}
running on http://www.compileonline.com/compile_cpp11_online.php gives:
Compiling the source code....
$g++ -std=c++11 main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1
Executing the program....
$demo
Result:
TYPEA ACTION: 2
String2 ACTION String1
I'd personally favour making the functor const. Instead, I like to bind the functor arguments to references:
static std::string emitWork(std::vector<MyVariantType> const listOfVariants) {
int sum = 0, charCount = 0;
std::stringstream os;
BOOST_FOREACH(MyVariantType const& v, listOfVariants) {
boost::apply_visitor(
boost::bind(MyCommandVisitor(), _1, boost::ref(os), boost::ref(sum), boost::ref(charCount)),
v);
}
return os.str();
}
Note that
emitWork can now be static, reentrant etc.
the operator() can now be const
The rest of the visitor would look like this:
struct MyCommandVisitor : boost::static_visitor<> {
void operator()(TypeA const& t, std::stringstream& os, int& sum, int& /*charCount*/) const {
sum += t.varA;
os << "TYPEA ACTION: " << t.varB << std::endl;
}
void operator()(TypeB const& t, std::stringstream& os, int& /*sum*/, int& charCount) const {
charCount += t.varA.size();
os << t.varB << " ACTION " << t.varA << std::endl;
}
};
See it Live On Coliru
I thought I was doing this right but it doesn't seem to be working. I'm basically experimenting with a queue and it works fine with one data type but now I'm trying to add multiple(in the end I want to have a int and a list of ints).
Here's the code:
#include <iostream>
#include <queue>
using namespace std;
int main()
{
struct product {
int x;
int y;
} ;
queue<product> q;
q.push(100, 100);
q.push(200, 100);
q.push(300, 100);
q.push(400, 100);
cout << "Size of the queue: " << q.size() << endl;
while (!q.empty()) {
cout << q.front() << endl;
q.pop();
}
}
It works without the struct, but obviously it only accepts one variable for each item in the queue that way. Is there a way to have multiple items?
I think the type specified for the template type cannot be a local definition. Change to:
struct product {
int x;
int y;
} ;
int main()
{
As others have already stated, add a constructor to product that accepts both arguments:
struct product {
int x;
int y;
product(int a_x, int a_y) : x(a_x), y(a_y) {}
};
...
q.push_back(product(100, 100));
You could also overload operator<< for outputting a product:
std::ostream& operator<<(std::ostream& a_out, const product& a_p)
{
a_out << "product(" << a_p.x << ", " << a_p.y << ")";
return a_out;
}
while (!q.empty()) {
cout << q.front() << endl;
q.pop();
}
The queue::push method expects one parameter, which must be of the type of your queue. Try it like this:
queue<product> q;
q.push(product(100, 100));
q.push(product(200, 100));
q.push(product(300, 100));
q.push(product(400, 100));
You'd also have to define a constructor for your struct:
struct product {
int x;
int y;
product(int _x, int _y) : x(_x), y(_y) {}
} ;
Here's how your main should look like. Note the addition of the constructor product(int i, int j), and the use of the constructor in adding elements to q.
int main ()
{
struct product {
int x;
int y;
product (int i, int j) : x(i), y(j) {}
} ;
queue<product> q;
q.push(product (100, 100));
q.push(product (200, 100));
q.push(product (300, 100));
q.push(product (400, 100));
cout << "Size of the queue: " << q.size() << endl;
while (!q.empty()) {
cout << q.front().x << ", " << q.front().y << endl;
q.pop();
}
return 0;
}
q.push(100, 100) is invalid, queue::push() takes only one parameter. You will need to push a product instead:
product p(100, 100);
q.push(p);
Then you have both 100s in the queue (stored in the product stucture).
If you want to store both a product1 and a product2, you will need a common base structure that both extends and store pointers (to the base) instead of the values themselves (to avoud slicing). At this point you might as well use class instead of struct