Use vectors!
#include <vector>
int a,b;
cin>>a>>b;
vector<int> InnerVector(a, 0);
vector<vector<int> > OuterVector(b, InnerVector);
Use vectors!
#include <vector>
int a,b;
cin>>a>>b;
vector<int> InnerVector(a, 0);
vector<vector<int> > OuterVector(b, InnerVector);
Interesting, it works if I make the vector of pointers const:
template <class T>
vector<T> DereferenceVector(const vector<T*> &PointerVec)
So I guess it was just a const problem and I thought I was doing something wrong with the template!
Also, I edited the original post once, but then I tried to edit it again but there was no "Edit" button - why is that?
Dave
I want to do something like this
template <class T>
vector<T> DereferenceVector(vector<T*> &PointerVec)
{
vector<T> ObjectVec;
for(unsigned int i = 0; i < PointerVec.size(); i++)
ObjectVec.push_back(*PointerVec[i]);
return ObjectVec;
}
and call it with
void TestDereferenceVector()
{
vector<double*> a(10);
vector<double> b = DereferenceVector(a);
}
That seems to work. But if I do
void TestDereferenceVector()
{
vector<vgl_point_3d<double>*> a(10);
vector<vgl_point_3d<double> > b = DereferenceVector(a);
}
/media/portable/Projects/src/ModelFile/ModelFile.h:304: error: no matching function for call to 'DereferenceVector(const std::vector<vgl_point_3d<double>*, std::allocator<vgl_point_3d<double>*> >&)'
Why would it not work with a more complex type?
Thanks,
Dave
Yea, I'd guess 'size' is either a "reserved word" (not technically?) - just try to rename the variable and see if that works.
Why not try the easy way to read files?
ifstream fin(Filename.c_str());
if(fin == NULL)
cout << "Cannot open file." << endl;
vector<string> Lines;
string line;
while(getline(fin, line))
{
Lines.push_back(line);
}
cout << "NumLines: " << Lines.size() << endl;
for(unsigned int i = 0; i < Lines.size(); i++)
cout << Lines[i] << endl;
I've never done this, but it doesn't look you passed any arguments? What about
system("FileName.exe arg1 arg2");
But look how easy this is!
ifstream fin(Filename.c_str());
if(fin == NULL)
cout << "Cannot open file." << endl;
vector<string> Lines;
string line;
while(getline(fin, line))
{
Lines.push_back(line);
}
cout << "NumLines: " << Lines.size() << endl;
for(unsigned int i = 0; i < Lines.size(); i++)
cout << Lines[i] << endl;
Why post 500 lines of code? Can you simplify the code to < 20 lines so we can look at it?
Why not use a vector<string>? Then you can use getline() :)
Why would you ever use a pointer to a pointer? Seems like its just asking for problems?
That is a linker error - you'd have to setup your project to compile linestorage.cpp.
write
[ code ]
YOUR CODE
[ /code ]
but without the spaces between the brackets and the word code. This will make it show up nice and organized like it did in my reply.
That is like saying ok I want to talk to this guy in French... I know he is French... now what do I do?
It may be because you have a semicolon at the end of this line:
while(mod_number2 = i%1);
Try removing that. Also, please use [ CODE ] tags around your code - what you posted was very difficult to read.
Dave
Yep, the const is just so you stop yourself from accidentally changing it if you don't want to change it. The reference is so it does not get copied by value which, as you say, is to save memory and I guess time. Even though you can't change it, the reference means you are looking at the values from the original variable.
You will need to use the c_str() function of the string because a lot of these function accept an array of characters, not an actual string.
#include <string>
using namespace std;
string filename = "whatever.txt";
fstream fio(filename.c_str(), ios::in | ios::out | ios::binary | ios::trunc);
Dave
I rarely need to use it. If you are within the scope of the class, MyVariable is the same as this->MyVariable. It is sometimes just nice for other people that read your code so that they know where these variables reside.
Dave
I always pass things as const if the function will not change them. Also you should pass anything bigger than a single int or double by reference. Both techniques are shown here:
int compare(const string &target, const string &s)//outputs # of correct characters
{
int alike = 0;
for (int i = 0; (unsigned int)i < target.length(); i++)
{
if (target[i] == s[i]) alike++;
}
return alike;
}
Goodluck!
Dave
haha yes, but I meant c++ style vs c-style.
If I do this, I get "warning: address of local variable returned".
unsigned char* CharArray(void) const
{
unsigned char arr[3];
arr[0] = R_;
arr[1] = G_;
arr[2] = B_;
return arr;
}
So the reason for that is that the memory allocated for arr[] is only available within the scope of the function CharArray?
So instead do I do this:
unsigned char* CharArray(void) const
{
unsigned char* arr = new unsigned char[3];
arr[0] = R_;
arr[1] = G_;
arr[2] = B_;
return arr;
}
Or I could pass a reference and fill it? How would I do that?
void CharArray(unsigned char* &arr)
{
arr[0] = R_;
arr[1] = G_;
arr[2] = B_;
}
main()
{
unsigned char arr[3];
CharArray(arr);
}
Like is it a reference to a pointer? Or is it just
void CharArray(unsigned char &arr)
That seems like it is just a reference to a single unsigned char, not an array of them.
Which is the most modern (ie c++) way to do this?
Thanks!
Dave
Give it a try and then we'll help.
This is called casting. The c++ style way to cast is
total_gal_paint = static_cast<int> ( (total_area / coverage_gallon_paint) + (0.9999) );
The code DemonGal711 posted is exactly the same thing as far as I know, its just a little "c style" :)
Also, it would be much easier if you posted the code using CODE tags rather than posting jpgs.
Dave
You should post only problematic section of the code, not the entire file!
getline(istream& fin, string& num_of_isbn, char '\n');
You need declare these variables and then pass them to the function, ie
istream fin;
string num_of_isbn;
char a;
getline(fin, num_of_isbn, a);
The & will be in the actual function definition (not the line that you call the function from) and means to accept the variable by reference instead of by value.
Dave
Sorry, I have no idea what this even is.
I would search for
boostnb.h or boostnb.cpp, because boostnb.o won't be made until you compile boostnb.cpp into the .o !
Also, please use code tags for only the code!
That is a linking error. You need to either link to the library, ie
g++ yourfile.cpp -l lTheLibrary
or actually compile the source along with yours (if you have it)
g++ yourfile.cpp TheFileTheFunctionIsIn.cpp
Unfortunately, this sounds like a big set of libraries and they are usually horribly documented, so you may have to do a bit of googling/greping.
Also, please use code tags when you post code.
Hope that helps.
Dave
I am trying to make a simple demo of a DataGridView bound to a database table. I want to add a row, delete a row, and save the table.
I used the IDE to do just about everything. It created the BindingSource when I set the datasource of the DataGridView to a table of a DataSource I added to the project.
Now the only code looks like this:
Public Class Form1
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'TestDataSet._Event' table. You can move, or remove it, as needed.
Me.EventTableAdapter.Fill(Me.TestDataSet._Event)
cmbReason.SelectedIndex = 0
End Sub
Private Sub btnDeleteRow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteRow.Click
DirectCast(Me.EventBindingSource.Current, DataRowView).Delete()
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Me.EventTableAdapter.Update(Me.TestDataSet)
End Sub
Private Sub btnAddRow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddRow.Click
Dim NewEvent As DataRowView = DirectCast(Me.EventBindingSource.AddNew, DataRowView)
'add all the attributes to the new row
NewEvent.Item("associate") = "Test"
NewEvent.Item("inout") = "IN"
NewEvent.Item("reason") = cmbReason.SelectedItem
NewEvent.Item("timefield") = Now
NewEvent.EndEdit() 'commit
End Sub
End Class
I set the AutoIncrementStep to 1 in my Key field in the dataset (the .xsd). I left the Key field visible in the DataGridView and it seems to be adding the correct Key when a row is added. However, I still occasionally get the "concurrency violation" error if I …
You may want to simplify the question to a single case. Once you get an answer you should be able to apply it to the rest of the cases. It just is overwhelming to people reading to look at 1000 lines of code that you post. Also, please wrap the code in CODE tags.
A friend convinced me to store a vector of pointers in my class:
vector<Point*> Points;
In my class instead of a vector of "real" objects (what do you call this?). The problem now is that there are several functions (out of my control ie. in a library) that accept a vector<Point>. I've been calling
vector<Point> PointersToReal(vector<Point*> &P)
{
vector<Point> Points;
for(int i = 0; i < P.size(); i++)
{
Points.push_back(*P[i]);
}
return Poitns;
}
Then calling the function, then calling
vector<Point*> PointersToReal(vector<Point> &P)
{
vector<Point*> Points;
for(int i = 0; i < P.size(); i++)
{
Points.push_back(new Point(P[i].x(), P[i].y(), P[i].z()));
}
return Poitns;
}
This just seems like a horrible horrible idea. Is there a standard solution? Or are you not supposed to store pointers if you have to pass real objects?
Thanks,
Dave
I have a function that I call recursively, but I want to keep track of a maximum through the entire process.
This is what I am doing:
void Intersect(double &MaxDistance)
{
if(something)
MaxDistance = something;
Intersect(MaxDistance);
}
Is that correct/reasonable? Something doesn't seem to be working and I'm having a hard time debugging because it's recursive (and I've rarely dealt with recursive functions).
Any suggestions?
Thanks,
Dave
It is very easy if you combine the two into a struct as Ancient Dragon suggested (full code listing below). However it still seems reasonable to ask for the indexes of the sort (as you can do in Matlab if anyone is familiar with that) rather than just the resulting sorted vector.
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
struct NumberName
{
int index;
string Name;
};
bool operator<(NumberName NN1, NumberName NN2)
{
return NN1.index < NN2.index;
}
int main (int argc, char *argv[])
{
vector<string> Names;
Names.push_back("Name1");
Names.push_back("Name2");
Names.push_back("Name3");
vector<int> Ints;
Ints.push_back(4);
Ints.push_back(1);
Ints.push_back(7);
vector<NumberName> Pairs(Names.size());
for(int i = 0; i < Names.size(); i++)
{
Pairs[i].index = Ints[i];
Pairs[i].Name = Names[i];
}
sort(Pairs.begin(), Pairs.end());
for(int i = 0; i < Pairs.size(); i++)
{
cout << Pairs[i].index << " " << Pairs[i].Name << endl;
}
return 0;
}
HA! I just noticed that was my thread lol. I still really can't believe that there is no built in mechanism to do this??
There was another thread about this (http://www.daniweb.com/forums/thread114737.html) but it didn't seem to be resolved?
If I have a vector of int's and another vector of the same length of corresponding names, I would like to sort the ints and have the names "follow"
vector<string> Doubles;
Doubles.push_back("Name1");
Doubles.push_back("Name2");
Doubles.push_back("Name3");
vector<int> Ints;
Ints.push_back(4);
Ints.push_back(1);
Ints.push_back(7);
sort(Ints.begin(), Ints.end());
for(int i = 0; i < Ints.size(); i++)
{
cout << Ints[i] << endl;
}
Now I would like the names to be sorted in the same order, ie. Name2, Name1, Name3.
There is a 3rd parameter of the sort() function, but I don't understand how to use it. Can someone shed some light?
Thanks,
Dave
You should simplify the problem. This problem has nothing to do with a bank, so why mention a bank? Ask something like
I want to input a line like
"MyName 2.3 4.5 6.7"
and store the input in a string and 3 doubles. How do I do that?
Dave
Is there one of those in c++?
double P = 3.5/(.1 * sqrt(2.0*3.14159)) * exp(-pow(5.0,2) / (2.0*pow(.1,2)));
cout << P << endl;
if (P==0)
cout << "P is zero!" << endl;
Is this underflowing so it is getting rounded to zero? The problem is that I am taking the log of this, so if it is zero it breaks everything because it is -inf instead of a normal double. Is there a way to prevent this?
Thanks,
Dave
So here's what I've got
void Pause(void)
{
char ch;
while ( cin.get ( ch ) && ch != '\n' );
cin.get(); //pause the program
}
void TestPause()
{
cout << "hello" << endl;
Pause();
cout << "goodbye" << endl;
}
It's pretty close... I have to hit enter twice though to continue the program. Is there a way to make it so one "enter" will do it?
Dave
my previous question still holds (about how to do this the c++ way) - but I figured out that it was my environment (KDevelop) that was producing this very odd behavior - if I run the executable from a terminal it works correctly - so I'm inquiring with the KDevelop people - the good news is that it's not a c++ issue!
It'd still be nice to get all this c style junk (ahem, code) out of my code though!
Dave
So if I look at something like this:
#include <istream>
void ignore_line ( std::istream& in )
{
char ch;
while ( in.get ( ch ) && ch != '\n' )
;
}
I'd want to turn it into:
#include <istream>
void Pause()
{
char ch;
while ( in.get ( ch ) && ch != '\n' );
}
Of course, "in" isn't declared... what would I have to pass Pause() (ie. how do I call it?) so that a pause effect is achieved?
Also, there shouldn't be anything in the input stream because I am doing no other keypressing in the program, right?
David
I wrote a pause function:
void Pause(void)
{
printf("Paused...\n\n");
fgetc(stdin);
}
It generally works fine (hit enter to continue). But one program doesn't seem to want to stop at all...
if(P == 0)
{
cout << "P=0!" << endl;
//just as another attempt to stop it , should stop here and ask for input
int a;
cin >> a;
//should stop here for input as well
Pause();
}
The output is this (and I never hit any keys):
0
P=0!
Paused...
0
P=0!
Paused...
0
P=0!
Paused...
Any idea why this wouldn't be stopping??
Thanks,
Dave
It's not that counterintuitive. I'm using some minimization software that calls my function a whole bunch of times. In those cases, I don't want to output anything to the screen. But if I call my function manually (from main() for example), then I would like to see some output. It is a restriction of the library that the function must only take certain parameters, so it is not possible to simply pass a flag as you suggest.
Dave
Is there anyway to get the calling function?
ie
void A()
{
if (A() was called from B() )
do something;
else
do something else
}
Is this possible?
Dave
oh sorry, that was correct, i just posted it wrong.
However, I found the problem. It was simply that I was not linking to the probability.cpp. So I guess when a virtual function definition is not found it gives that vtable error?
Thanks,
Dave
In integration.h I have this
class FunctionClass
{
public:
virtual double f(const double x) = 0;
};
Then in probability.h, I have this
#include "integration.h"
class Mass1 : public FunctionClass
{
public:
double Clutter;
Mass1(double c) : Clutter(c) {}
double f(const double x)
{
return Clutter * exp(-Clutter * x);
}
};
That works perfectly. However, if I change it to
#include "integration.h"
class Mass1 : public FunctionClass
{
public:
double Clutter;
Mass1(double c) : Clutter(c) {}
double f(const double x);
};
and then in probability.cpp put
#include "probability.h"
double f(const double x)
{
return Clutter * exp(-Clutter * x);
}
I get this vtable error. What have I done wrong?
Thanks,
Dave
Thanks for the discussion guys - gives me something to think about.
First of all, it would be, at the very least, Scanner::Scanner(int NumPoints, RangeStep& Theta, RangeStep& Phi, Point Location, Transformation T, double PointSpeed) , or even something more clumpy. I suspect I'd only have 2 or 3 parameters to the constructor, the rest part of helper classes.
What do you mean "helper classes"? Can you give a brief example of how to break that constructor into
Scanner::Scanner(Transformation T)
and a helper class?
but the constructor really looks like
Scanner::Scanner(int NumPoints, int MinTheta, int MaxTheta, int ThetaStep, int MinPhi, int MaxPhi, int PhiStep, Point Location, Transformation T, double PointSpeed)
It seems absolutely crazy to me to construct a new Scanner when all that needs to be changed is the location, no?
I don't understand how you would not need mutators...
class Scanner
{
Point Location;
Scanner(Point &Loc) : Location(Loc) {}
};
int main()
{
Scanner MyScanner(Point(0,1,0));
//now how do I move the scanner to a new location without a mutator setLocation() ?
return 0;
}
What do you think of that example?
Dave
I guess I don't know the difference between using class and writing object oriented programs? I thought an object oriented program was one which used classes (aka objects)?
What I have is a Scanner class and a Scan class. I do something like this
Scanner MyScanner;
Scan MyScan = MyScanner.TakeScan();
Is that enough to tell you which kind of programming this is?
Dave
Ok - but for simple cases (just like this one, where all it is doing is storing a number), it's not bad practice to just make it public?
Often times I just have a huge list of properties:
int NumPoints;
double ThetaMin, ThetaMax, PhiMin, PhiMax, PhiStep, ThetaStep;
And the list goes on and on.... then I have to write accessors and mutators for allllll of those, and the header becomes very cluttered.
Know what I mean?
Dave