c++ How to use a ctor from another ctor? [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calling another constructor when constructing an object with const members
I want the latter to use the former. How can i do that in c++?. If it's not possible why can't i make the *this = regMatrix assignment?
RegMatrix::RegMatrix(int numRow,int numCol)
{
int i;
for(i=0;i<numRow;i++)
{
_matrix.push_back(vector<double>(numCol,0));
}
}
RegMatrix::RegMatrix(const SparseMatrix &sparseMatrix)
{
RegMatrix regMatrix(sparseMatrix.getNumRow(),sparseMatrix.getNumCol());
vector<Node> matrix = sparseMatrix.getMatrix();
cout << "size: " << matrix.size() << endl;
for(std::vector<Node>::const_iterator it = matrix.begin(); it != matrix.end(); ++it )
{
cout << "Position: [" << (*it).i << ", " << (*it).j << "] Value:" << (*it).value << endl;
regMatrix._matrix[(*it).i][(*it).j] = (*it).value;
}
*this = regMatrix;
}

You can do this in the new C++0x using "Delegated Constructors".
`
RegMatrix(const SparseMatrix &sparseMatrix) : RegMatrix(sparseMatrix.getNumRow(),sparseMatrix.getNumCol())
{
vector<Node> matrix = sparseMatrix.getMatrix();
cout << "size: " << matrix.size() << endl;
for(std::vector<Node>::const_iterator it = matrix.begin(); it != matrix.end(); ++it )
{
cout << "Position: [" << (*it).i << ", " << (*it).j << "] Value:" << (*it).value << endl;
this->_matrix[(*it).i][(*it).j] = (*it).value;
}
}
`

Related

How to print correctly const char* struct member of a list?

I am trying to display struct members of a list in OMNeT++, all members are displayed correctly unless the member which is of type const char*. I am confused because after three push_back in the list, when I display. All the members of the last pushed element is displayed correctly even the one of type const char*. But for the two first pushed elements, the member of type cont char* display nothing, garbage or "DETAIL (Ipv4)Drones.host[3].ipv4.ip".
Ipv4Address srcAddress = recMtlsd->getSrcAddress();
Ipv4Address dstAddress = recMtlsd->getDstAddress();
const char* position = recMtlsd->getPosition();
simtime_t time = recMtlsd->getTime();
int srcID = recMtlsd->getId();
EV_DEBUG << "Source : " << srcAddress << endl;
EV_DEBUG << "Destination : " << dstAddress << endl;
EV_DEBUG << "Position : " << position << endl;
EV_DEBUG << "Time : " << time << endl;
EV_DEBUG << "Source ID: " << srcID << endl;
// All precedent displays are working correctly
/*typedef struct Mtlsd{
Ipv4Address originatorAddr, destinationAddr;
const char *position;
int originatorId;
simtime_t time;
}MTLSD;*/
MTLSD recitem;
recitem.originatorAddr = srcAddress;
recitem.originatorId = srcID;
recitem.destinationAddr = dstAddress;
recitem.position = position;
recitem.time = time;
EV_DEBUG << "Source : " << recitem.originatorAddr << endl;
EV_DEBUG << "Destination : " << recitem.dstinationAddr << endl;
EV_DEBUG << "Position : " << recitem.position << endl;
EV_DEBUG << "Time : " << recitem.time << endl;
EV_DEBUG << "Source ID: " << recitem.srcID << endl;
// All precedent displays are working correctly
/*typedef struct Mtlsd_data{
list<MTLSD> q;
int ID;
}MTLSD_DATA;*/
list<MTLSD_DATA> mtlsd_file;
auto node = find_if(mtlsd_file.begin(), mtlsd_file.end(), [=] (MTLSD_DATA const& i){return (i.ID == srcID);});
bool found = (node != mtlsd_file.end());
if (!found)
{
MTLSD_DATA recdata;
recdata.ID = srcID;
recdata.q.push_back(recitem);
mtlsd_file.push_back(recdata);
EV_DEBUG << "For node " << srcID ;
for(auto claim=mtlsd_file.back().q.begin(); claim!=mtlsd_file.back().q.end();++claim)
{
EV_DEBUG << "(" << string(claim->position) << ", " << claim->time << ");" << endl;
}
// The precedent display works correctly
}
else
{
EV_DEBUG << "I already have data about the node " << node->ID << endl;
if (node->q.size() == 3)
{
EV_DEBUG << "I already have three time-location claim in the queue" << endl;
EV_DEBUG << "Here they are: ";
EV_DEBUG << "For node " << (*node).ID << endl;
for(auto fileclaim=(*node).q.begin(); fileclaim!=(*node).q.end();++fileclaim)
EV_DEBUG << "(" << string((*fileclaim).position) << ", " << (*fileclaim).time << ");" << endl;
EV_DEBUG << "I will delete the old one (" << node->q.front().position << ", " << node->q.front().time << ")" << endl;
node->q.pop_front();
}
node->q.push_back(recitem);
EV_DEBUG << "I have pushed this new one : (" << string(node->q.back().position) << ", " << node->q.back().time << ")" << endl;
}
EV_DEBUG << "Here they are all time-location claims in the queue : ";
for(auto fileclaims=node->q.begin(); fileclaims!=node->q.end();++fileclaims)
{
EV_DEBUG << "(" << string(fileclaims->position) << ", " << fileclaims->time << ");" << endl;
}
// The last element is displayed correctly, but those before not.
.
.
.

Get a mesh_3 'off' from Projection_traits_xy_3 constrained delaunay

I've computed a 2D constrained delaunay triangulation from 2.5D data using the projection_traits_xy_3 [1]. Now I would like to get a mesh that I can visualize.
I've managed to do that with 3d delaunay following the manual[2], how could I achieve it with a 2.5D CDT ?
[...]
typedef CGAL::Projection_traits_xy_3<K> Gt;
typedef CGAL::Constrained_Delaunay_triangulation_2<Gt, Tds> CDT;
[...]
CDT cdt;
cdt.insert(points.begin(),points.end());
[...]
¿?
[...]
std::ofstream out(outdir + "out.off");
Polyhedron output_mesh;
CGAL::output_surface_facets_to_polyhedron(¿?, output_mesh);
out << output_mesh;
[1] http://pastebin.com/HzAwrnW5
[2] http://doc.cgal.org/latest/Point_set_processing_3/index.html#chappoint_set_processing_3
http://doc.cgal.org/latest/Surface_reconstruction_points_3/
Here comes pseudocode forwriting it into an off file
cout << "OFF\n" << cdt.number_of_vertices()
<< " " << cdt.number_of_faces() << " 0" << std::endl;
std::map<vertex_handle,int> indices;
int counter = 0;
for all finite vertices v {
cout << v->point() <<std::endl;
indices.insert(v, counter++);
}
for all finite faces f {
cout << "3 " << indices[f->vertex(0)]
<< " " << indices[f->vertex(1)]
<< " " << indices[f->vertex(2)] << std::endl;
}
From #Andreas suggestion:
Here comes the code for writing it into an off file
std::ofstream outstream("output.off");
outstream << "OFF\n" << cdt.number_of_vertices()
<< " " << cdt.number_of_faces() << " 0" << std::endl;
std::map<CDT::Vertex_handle,int> indices;
int counter = 0;
for(CDT::Finite_vertices_iterator it = cdt.finite_vertices_begin(); it != cdt.finite_vertices_end(); ++it)
{
outstream << it->point() << std::endl;
indices.insert(std::pair<CDT::Vertex_handle,int>(it, counter++));
}
for(CDT::Finite_faces_iterator it = cdt.finite_faces_begin(); it != cdt.finite_faces_end(); ++it)
{
outstream << "3 " << indices[it->vertex(0)]
<< " " << indices[it->vertex(1)]
<< " " << indices[it->vertex(2)] << std::endl;
}

std::cout for map<string, int>

I have a map declared as follows
map<string, int> symbolTable;
if(tempLine.substr(0,1) == "("){
symbolTable.insert(pair<string, int>(tempLine, lineCount));
}
How do I std::cout all of the things in my symbol table?
In modern C++:
for (auto&& item : symbolTable)
cout << item.first << ": " << item.second << '\n';
If you only have access to a pre-C++11 compiler the code would be:
for ( map<string, int>::const_iterator it = symbolTable.begin(); it != symbolTable.end(); ++it)
cout << it->first << ": " << it->second << '\n';
Here's an alternative if your compiler isn't C++11 compliant:
for (map<string, int>::iterator it = symbolTable.begin();
it != symbolTable.end(); ++it)
{
cout << it->first << " " << it->second << endl;
}
And for completeness, if it is:
for (auto& s : symbolTable)
{
cout << s.first << " " << s.second << endl;
}
You can use a loop to print all the key/value pairs. The code following is an example in C++11
for (const auto& kv : symbolTable) {
std::cout << kv.first << " " << kv.second << '\n';
}
ps: Both of other two answers pay little attention to const, which is quite sad...

Why does a nullptr terminated array passed to function through ***char loose the termination element? [duplicate]

This question already has answers here:
Passing a char pointer array to a function
(2 answers)
Closed 8 years ago.
Note 1: I am not looking for different solutions to the problem at hand. I'm curious about what actually is happening here.
Note 2: I'm doing this in c++ context, but am assuming that this also applies to C, hence the C tag. (apart from the representation of a null pointer)
This is about c-strings and access to original from a function. I'll use argv and argc to illustrate that the array should be nullptr terminated. I declare them like this:
int argc = 1;
char **argv = (char**) malloc( (argc + 1) * sizeof(char*) );
argv[0] = (char*)"argument 0";
argv[1] = nullptr;
If I declare a function like this: func1(int &f_argc, char **f_argv) I can access all elements inside the function scope, including f_argv[f_argc], which is nullptr, but I cannot modify the original argv to point to a different address as f_argv in the function is a value passed copy of the original pointer. It has a different address in memory.
If I declare the function like this instead: func2(int &f_argc, char ***f_argv), I can access the original argv through *f_argv in the function, but the last element (which should be nullptr) is cut off. This means that if I try to check for the terminating nullptr inside the function, I try to access an element outside the range of the array, resulting in a core dump at runtime.
Q1: Why is f_argv cut off when reaching the nullptr in func2, but not in func1?
Q2: Is there a way to get write access to the original argv from within the function, without removing the terminator?
Edit: (added code to show what I mean)
#include <iostream>
#include <cstring>
void func1(int &f_argc, char **f_argv) {
using std::cout;
using std::endl;
cout << " In function:" << endl;
cout << " argv passed as **f_argv" << endl;
cout << " f_argv = " << f_argv << " , &f_argv = " << &f_argv << endl;
for (int pos = 0; pos < f_argc; pos++) {
if (f_argv[pos] != nullptr) {
cout << " f_argv[" << pos << "] = \"" << f_argv[pos] << "\"" << endl;
} else {
cout << " f_argv is prematurely terminated" << endl;
}
}
if (f_argv[f_argc] == nullptr) {
cout << " f_argv is correctly terminated" << endl;
} else {
cout << " f_argv[" << f_argc << "] = \"" << f_argv[f_argc] << "\"" << endl;
cout << " f_argv is not terminated" << endl;
}
// Intention is to copy argv here, add elements, terminate it with
// nullptr and change original argv to point to copy. This wouldn't
// work in this function, as &f_argv != &argv.
return;
}
void func2(int &f_argc, char ***f_argv) {
using std::cout;
using std::endl;
cout << " In function:" << endl;
cout << " array passed as ***f_argv" << endl;
cout << " f_argc = " << f_argc
<< " , &f_argc = " << &f_argc << endl;
cout << " *f_argv = " << *f_argv
<< " , f_argv = " << f_argv << endl;
for (int pos = 0; pos < f_argc; pos++) {
cout << " about to check: "
<< "if (*f_argv[" << pos << "] != nullptr)" << endl;
if (*f_argv[pos] != nullptr) {
cout << " *f_argv[" << pos << "] = \""
<< *f_argv[pos] << "\"" << endl;
} else {
cout << " *f_argv is prematurely terminated" << endl;
}
}
if (*f_argv[f_argc] == nullptr) {
cout << " *f_argv is correctly terminated" << endl;
} else {
cout << " *f_argv[" << f_argc << "] = \""
<< *f_argv[f_argc] << "\"" << endl;
cout << " *f_argv is not terminated" << endl;
}
// Intention is to copy argv here, add elements, terminate it with
// nullptr and change original argv to point to copy.
return;
}
// --------------------------------------------
int main() {
using std::cout;
using std::endl;
int argc=1;
char **argv = (char**) malloc( (argc + 1) * sizeof(char*) );
argv[0] = (char*)"argument 0";
argv[1] = nullptr;
cout << "Before function call" << endl;
cout << "argv = " << argv << " , &argv = " << &argv << endl;
for (int i = 0; i < argc; i++) {
if (argv[i] != nullptr) {
cout << "argv[" << i << "] = \"" << argv[i] << "\"" << endl;
} else {
cout << "argv is prematurely terminated" << endl;
}
}
if (argv[argc] == nullptr) {
cout << "argv is correctly terminated" << endl;
} else {
cout << "argv[" << argc << "] = \"" << argv[argc] << "\"" << endl;
cout << "argv is not terminated" << endl;
}
// run one of these
//func1(argc, argv);
func2(argc, &argv);
free(argv);
return 0;
}
If running func2, running the program results in a core dump at this line:
if (*f_argv[f_argc] == nullptr) {
The subscript operator has higher precedence than the dereference operator. *f_argv[f_argc] is *(f_argv[f_argc]). What you want is (*f_argv)[f_argc].
Since you are using C++, you should consider taking f_argv by reference - void f(int &f_argc, char **& f_argv);.

top 5 value via vector iterator using function

Hi all I'm having compilation error when I'm using vector iterator in a function itself.
i've tried executing the example from http://ideone.com/tTDYU5 and it works perfectly fine. However when I try to put it in a function things gets ugly why is this so?
vector <PointTwoD> topfive;
void MissionPlan::topfives()
{
topfive.assign( point1.begin(), point1.end() );
sort(topfive.begin(), topfive.end(), sortByCiv);
}
void MissionPlan::DisplayTopFiveResult()
{
missionplan.topfives();
vector<PointTwoD>::iterator it = topfive.begin();
for (int i = 0; i < 5 && it != topfive.end(); i++) {
cout << "X axis: " << pointtwoD.xcord << " " << "Y axis: " << pointtwoD.ycord << " " << "CIV Index: " << pointtwoD.civIndex << *it;
++it;
}
}
Since "the value are all in the class PointTwoD "
Use it to print those :
vector<PointTwoD>::iterator it = topfive.begin();
for (int i = 0; i < 5 && it != topfive.end(); i++) {
cout << "X axis: " << it->xcord << " "
<< "Y axis: " << it->ycord << " "
<< "CIV Index: " << it->civIndex << std::endl;
++it;
}
If still this throws compilation error, you need to provide more info.