Monday, May 24, 2010

Eigenvectors calculation (from Numerical Recipes in C book)?

Hi,


I implemented the algorithms tred2() (page 474) and tqli() (page 480) for calculating eigenvectors and eigenvalues of real matrices, and comparing the results to the ones obtained with MatLab, some of the eigenvectors have the opposite sign. Every single value is ok, but the vector seems to be multiplied by -1.





Does anyone know why is this, and if this is actually an error?





Thanks in advance.





PS: the book can be found online at





http://www.nr.com/nronline_switcher.php

Eigenvectors calculation (from Numerical Recipes in C book)?
Eigenvectors are not unique. If your matrix has an eigenvector of





[ 1, -2]'





for example, then any multiple of that eigenvector is also an eigenvector for that hypothetical matrix, so





[2, -4]'


[50, -100]'


[-1, 2]'


[-1000, 2000]'





are all eigenvectors for this hypothetical matrix. That is because for any square matrix A with eigenvector x corresponding to eigenvalue λ and for any constant c





A(c*x) = c*Ax


= c*λx


= λ(c*x)





Which means that c*x is an eigenvector for A.





So, there is no error. Some are just multiplied by -1. You're good.





edit: No, the eigenvalues do not change. Note in my "proof" above that the same eigenvalue λ was used for the vectors x and c*x. Like I said, eigenvectors aren't unique; not even for a particular eigenvalue.





Here's an example.





A =


[ 4 -2 ]


[ 1 1]





x =


[ 2 ]


[ 1 ]





Ax =


[ 6 ]


[ 3 ]


= 3x





So x is an eigenvector of A with an eigenvalue of 3. Now let's look at y = -x = [-2 -1]'.





Ay =


[ -6 ]


[ -3 ]


= 3y





So y = -x is also an eigenvector of A with an eigenvalue of 3.





I can't message you, so send me a message if you have any questions.


AS Basic as it can get C++ Hangman?

i need help in hangman only using %26lt;iostream%26gt;, %26lt;lvp\string%26gt;, %26lt;lvp\vector%26gt; or bool..

AS Basic as it can get C++ Hangman?
wow, thats a great question... lets see... my answer is... around the corner


Can anyone write this code for c++?

Write a function that computes the alternating sum of all elements in a


alternating_sum is called with a vector containing


1 4 9 16 9 7 4 9 11


Then it computes


1 – 4 + 9 – 16 + 9 – 7 + 4 – 9 + 11 = -2

Can anyone write this code for c++?
Take a look at here:





http://www.msoe.edu/eecs/cese/resources/...


Finding the mode of an array C++?

I have a vector that records the number of occurances based on user input, but I cannot figure out how to find the mode of that data here is my code listing the occurances and what I have so far for the mode:





cout%26lt;%26lt;"Roll"%26lt;%26lt;" "%26lt;%26lt;"Count"%26lt;%26lt;endl;


for(num = 1; num %26lt;=50;num++){


cout%26lt;%26lt;num%26lt;%26lt;" "%26lt;%26lt;Count[num]%26lt;%26lt;endl;


}





void Mode(CountType %26amp;Count, int %26amp;num, int %26amp;i)


{





int pos_mode;


int mode;


for(pos_mode = 1; pos_mode %26lt;=50;pos_mode++){


if (Count[pos_mode] %26gt; Count[num]){


mode = pos_mode;





}

















}


cout%26lt;%26lt;"The mode is: "%26lt;%26lt;mode;


}

Finding the mode of an array C++?
Try this:





I'm assuming CountType to be integer.





void Mode(CountType* Count)


{


//first sort the count array yourself





int n = 0;


int count = 0;


int max = 0;


int mode = 0;





for(int i = 0;i%26lt;50;i++)


{





if(n != Count[i])


{


n = Count[i];


count = 1;


}


else


{


count++;


}





if(count %26gt; max)


{


max = count;


mode = n;


}





}





cout%26lt;%26lt;"Mode: "%26lt;%26lt;mode%26lt;%26lt;endl;


}








Don't forget to sort the array first, it is important.

phone cards

How do you make a C++ histogram?

for the program i need a function that displays a histogram showing the numbers (that the user has given using a vector) in each 5 five unit range (i.e. 1-5,6-10

How do you make a C++ histogram?
The trick to this is using the proper coding structure... a switch statement. A histogram is basically a bar chart that shows relative frequencies (total counts for a given value... how many fives, how many eights etc) so that you can see a distribution of values.





int firstrange = 0;


int secondrange = 0;


int thirdrange = 0;


int howmanyunknowns = 0;





for(int i=0;i %26lt; int_Vector.size(); i++)


{


int d = int_Vector.at(i);





switch (d) {


case 1:


case 2:


case 3:


firstrange++;


break;





case 4:


case 5:


case 6:


secondrange++;


break;





case 7:


case 8:


case 9:


thirdrange++;


break;





default:


howmanyunknowns++;


}





}





The above loop would run through a integer vector looking for 1's, 2's, 3's...etc and count them up, placing them in the correct range variable counter. (Values of 1, 2, 3 go into one variable... firstrange)





At the end you would have a count of each range for displaying as you like.





Granted this switch statement can only handle a limited set of ranges, but if you need more and bigger ranges, remember you can write a switch statement into a series of if statements...





if ((x %26gt;=1) %26amp;%26amp; (x %26lt;= 20)) { firstrange++; }


if ((x %26gt;=21) %26amp;%26amp; (x %26lt;= 40)) { secondrange++; }





etc etc etc.





Side Note: You could use a vector iterator instead of a for loop. I just used one to make it a bit more simple looking.





Hope you get the idea.


How do u program this c++ visual program using the following libraries?

Topic: Write a program that allows the user to enter numbers in the range 0-19, terminated by a sentinel, and then perform the following functiosn on the numbers: the average number, the maximum number, the range, the median





#include%26lt;iostream%26gt;


#include%26lt;vector%26gt;


#include%26lt;string%26gt;


#include%26lt;stdlib.h%26gt;


#include%26lt;time.h%26gt;





using namespace std;

How do u program this c++ visual program using the following libraries?
Try this:





cout %26lt;%26lt; "1"


cout %26lt;%26lt; "am 2"


cout %26lt;%26lt; "st"


cout %26lt;%26lt; "up"


cout %26lt;%26lt; "id"


cout %26lt;%26lt; "an"


cout %26lt;%26lt; "d la"


cout %26lt;%26lt; "zy 2"


cout %26lt;%26lt; "due"


cout %26lt;%26lt; "hom"


cout %26lt;%26lt; "e"


cout %26lt;%26lt; "work"
Reply:Why do you have to use those libs?





Looks like all you'd need is iostream.





int myInput=0;


do {


cout %26lt;%26lt; "Give me a number: ";


cin %26gt;%26gt; myInput;


if (myInput == -1) {


cout %26lt;%26lt; "C-ya!" %26lt;%26lt; endl;


}


else if (myInput %26lt; 0 || myInput %26gt;19) {


cout %26lt;%26lt; "Bad number... Try again!" %26lt;%26lt; endl;


}


else


numbersRead++;


numberTotal+=myInput;


if (myInput%26gt;maxNumber)


maxNumber=myInput;





and so on...





Your instructor would probably want you to complete it yourself.


I am trying to write a program with C++ which acts like an E-6B.?

I need an equation which will give me the wind vector, if i have the ground speed being 478 kts with a true heading 350, and a true airspeed of 500 kts and a true course of 355.

I am trying to write a program with C++ which acts like an E-6B.?
The wiki site has some fomulas you may find useful.


Distance between a point and a Vector.?

There is a vector from point A to B


VectorAB= %26lt; 4,1,-2%26gt;


Then there is a point C(4,1,2) .





What is the shortest distance between C, and vector AB?

Distance between a point and a Vector.?
You must know the coordinates of either A or B to answer this fully. As it is states, C could be in Vector AB. Thus, the shortest distance is zero.


**************************************...


UPDATE UPDATE UPDATE UPDATE UPDATE





OK. So point A is at (0,0,2) B is at (4,1,0) and point C is at C(4,1,2). Consider A, B, and C veritces of a triangle. Find the lengths of each side. Then, ignore the 3D stuff. Find the altitude of triangle ABC from C to side AB.





For lengths of sides, use


(x2-x1)^2 + (y2-y1)^2 + (z2-z1)^2 = d^2.





This works for this specific problem when distance is the main concern.





The previous poster has the hardcore, pure math method that works in more general cases.
Reply:Find the vector orthogonal to AB that passes through the point C. Then calculate the length of that vector.

orange

Binary error in C++? How to fix?

epsfile.open("EPS.DAT", ios::in);


if(epsfile)


{


do


{


epsfile %26gt;%26gt; epsfile[i];


i++;


}


while (epsfile[i - 1] !="End");


}


epsfile.close();

















Both places that the "[ ]" appear seem to be having issues, the compiler says that std::ifstream doesn't define the operator. No sure what to do to fix it. I have included iostream, ifstream, string, and vector. Is there something i'm missing?

Binary error in C++? How to fix?
As the compiler says, there is no operator[ ] for ifstream. The two statements where you're trying to index into epsfile are invalid. I'm not even sure what you're trying to do with the statement: epsfile %26gt;%26gt; epsfile[i]. I guess you're trying to read from the file, but your syntax is wrong.





Have a look here:


http://www.cplusplus.com/doc/tutorial/fi...


Help with an C++ homework question.?

i'm having problems creating and implementing the final requirment:void remove_message(int i) const;





This is my question:





You have to create a class called mailbox. You don't yet know how to store a collection of message objects. Instead, use the following brute force approach: The mailbox contains one very long string, which is the concatenation of all messages. You can tell where a new message starts by searching for a From: at the beginning of a line. This may sound like a dumb strategy, but surprisingly, many e-mail systems do just that.


Implement the following member functions:


void Mailbox::add_message(Message m);


Message Mailbox::get_message(int i) const;


void remove_message(int i) const;








I would appreciate any input or comments anyone can make about what I have so far and if what I am doing or trying to do makes sense.








class Mailbox


{


public:


Mailbox(string u);


void add_message(Message m);


Message get_message(int i) const;


int count_messages() const;


string get_user() const;


private:


vector%26lt;Message%26gt; messages;


string user;


};





Mailbox::Mailbox(string u)


{


user = u;


}





string Mailbox::get_user() const


{


return user;


}





void Mailbox::add_message(Message m)


{


messages.push_back(m);


}





Message Mailbox::get_message(int message_num) const


{


return messages[message_num];


}





int Mailbox::count_messages() const


{


return messages.size();


}

Help with an C++ homework question.?
The first problem with this is that you say you want to implement the function:





void remove_message(int i) const





This doesn't make sense, since only member functions can be declared const. Global functions can never be declared const. I assume you meant:





void Mailbox::remove_message(int i) const





The problem with this is that if this function is meant to effectively delete some data from the Mailbox class, then it is not legally allowed to do so because the function is declared as being const, which means it is not allowed to alter any members of the class of which it is itself a member.





However, the following would be legal:





void Mailbox::remove_message(int i)





In order to implement this in your version of the Mailbox class you would do:





void Mailbox::remove_message(int i)


{


messages.erase( members.begin() + i );





// Your compiler might not like the members.begin() + i.


// If this is the case use the following code instead





// std::vector%26lt; Message %26gt;::iterator itr;


// for ( int iCount = 0; iCount %26lt; i; iCount++ )


// {


// ++itr;


// }


// messages.erase( itr );


}





While your approach would work, it's not what you've been asked to do. The question states:





"You don't yet know how to store a collection of message objects. Instead, use the following brute force approach: The mailbox contains one very long string, which is the concatenation of all messages. You can tell where a new message starts by searching for a From: at the beginning of a line."





This means you shouldn't be using a member vector to store the messages. Instead you should be using a single very long string member to store all the messages, which you then parse to find a particular message. Basically, all the code you have to write is a bunch of string manipulation functions. I suggest you use a STL string object rather than a C style char array as this means you don't have to have a maximum string length for your storage string when you declare it nor do you have to manage the string's internal memory allocation yourself.





As you haven't included any details about the Message class I can't tell how you extract a string from a Message. Is Message a class/struct that has a string member, or is it just a typedef to std::string?


Help with an C++ assignment question.?

i'm having problems creating and implementing the final requirment:void remove_message(int i) const;





This is my question:





You have to create a class called mailbox. You don't yet know how to store a collection of message objects. Instead, use the following brute force approach: The mailbox contains one very long string, which is the concatenation of all messages. You can tell where a new message starts by searching for a From: at the beginning of a line. This may sound like a dumb strategy, but surprisingly, many e-mail systems do just that.


Implement the following member functions:


void Mailbox::add_message(Message m);


Message Mailbox::get_message(int i) const;


void remove_message(int i) const;








I would appreciate any input or comments anyone can make about what I have so far and if what I am doing or trying to do makes sense.








class Mailbox


{


public:


Mailbox(string u);


void add_message(Message m);


Message get_message(int i) const;


int count_messages() const;


string get_user() const;


private:


vector%26lt;Message%26gt; messages;


string user;


};





Mailbox::Mailbox(string u)


{


user = u;


}





string Mailbox::get_user() const


{


return user;


}





void Mailbox::add_message(Message m)


{


messages.push_back(m);


}





Message Mailbox::get_message(int message_num) const


{


return messages[message_num];


}





int Mailbox::count_messages() const


{


return messages.size();


}

Help with an C++ assignment question.?
You don't show how Message is defined, but with vector%26lt;Message%26gt;, which would probably give you a nicer implementation, I don't think you're doing what the assignment asks. Mailbox::messages needs to be a string; and for convenience, give Mailbox a count attribute.





The signature of add_message would be :


void Mailbox::add_message(const string%26amp; m);


It would use string's operator+= to concatenate m to messages, and then increment the count attribute. (Mailbox::remove_message decrements the count attribute, and count_messages just returns the current value of count.)





The string class provides various find operations you can use to search for a message, using the keyword "From:", that get_message or remove_message is looking for.





Assignments like this usually make you do something one way when you know there's an easier way to do it. So, use a string instead of your vector, and you'll probably learn a few things about all the good operations the string class provides.


Need help in dynamic arrays of c++?

how can i increase the size of a dynamic array even though i dont know what its end size will be...please tell me this without the use of std vector thingy..only use the basic stuff like while,for loops etc to do it..

Need help in dynamic arrays of c++?
Not an uncommon question.





Usually what's done is instead of increasing the size every time you insert something (it causes a large load on the processor)


you do the easier and less intensive process of doubling the size when you see that you need more space.





let's assume we have a dynamic array of books?


so:





const int START_SIZE = 5





Book* myArray = new Book[START_SIZE]





ok, now we know that when we have a dynamic array we must always keep track of it's capacity and it's size (usually you store those in variables).


Our new array has a capacity of 5 and since we didn't add anything it has a size of 0.





so:


int capcacity(5);


int size (0);





great!


We're on a roll, now let's say we add a book.


so the process of adding a book to the Dynamic array is the following





1.) first you check that your new size does not equal your capacity.





in our case if we add one book our capacity is still 5 and our new size (after adding a book ) is now 1.





that's great, so just say:


Book treasure_island("Treasure Island") ;


myArray[size] = treasure_island;


size++;





(keep in mind the order! It's important! arrays start storing at 0...)





ok, that works great as long as we have space, what do we do if we dont have anymore space!?!?!





well, first we have to do a check for that, so before we add a book we do:





size++; //our new size





if (size == capacity)


{


//double the capacity (or increase it however u want)


capacity = capacity *2;





//make a temporary array of that size


Book* tempArray = new Book [capacity];





//copy the old values across to the temp array





for (int i=0 ; i %26lt; size; i++)


{


tempArray[i] = myArray[i];


}





//delete the old array (otherwise a memory leak!)


delete [] myArray;





//make our array pointer point at the tempArray


myArray = tempArray;





}


// all done! now, we can add the new book knowing we have //space for it!





myArray[size] = (the book you wanted);








Hope this helps!
Reply:Well, even though you said not to use it, an stl vector really is the fastest and easiest way to do this, I'd recommend that over reinventing the wheel.





To "roll your own" using just the new/delete, you'll just have to keep track of the current maximum size of the array, and the number of items you've added. Whenever you add an item to the array, check if it would push the number of items over the maximum. If it will, you'll have to double (doubling is the most common, but you could increment it by some other amount if you want) the maximum, allocate a new array of the entire new maximum size, copy all the old elements over, and then delete the old array. If you look at the vector source, you'll see this is pretty much what it does when it goes beyond its size limit.





// initialize


int maxItems=100


int numItems=0;


itemType *array=new itemType[maxItems];





// ...


//... add something to array ...


if(numItems+1%26gt;=maxItems)


{


maxItems*=2;


itemType *newArray=new itemType[maxItems];


// in practice, memcpy and a for loop usually take


// about the same time for me, but this looks nicer


memcpy( newArray, array, sizeof ( itemType ) * numItems );


delete array;


array=newArray;


// note that the location of the array is now a new address


// so anything that was passed the location of the old array


// by reference now has a BAD pointer


}


array[numItems]=something;


numItems++;


// note that numItems is incremented only AFTER using


// it as the index. This could be written in 1 step as


// array[++numItems]=something; but it makes it a little less


// readable IMO








Ideally, the above would be in some dynamic array class, which overloads the [] operators for access, and has some add_item(itemType) method. And if you want to use it for different types, you'd really want to make it a template class. But then, this would be really close to stl vector, which you requested not using. In that case, maybe you do want to go linked list or tree as suggested above.
Reply:This is a bit complicated as you are going to have to dynamical cast the array size on the fly; however, the code will look something like this:





char * myArray = NULL;


// Demonstrate increasing the array based on loop iterations


// This code would cause errors and should only be used as


// a basic example of how to create dynamic arrays, all data


// is lost when the size is increased!


for (int ndx = 0; ndx %26lt; 10; ndx++) {


myArray = new char[ndx];


}


// Release the memory used


delete [] myArray;
Reply:You can just call a function to copy the array into a temporary array of the same size, delete the original array, and create a new array that is the size of the old array + 50 or so.





void lengthenArray(int/char/whatever *array) {


length = length of array;


int/char/whatever temp[length];


copy(array, temp);


delete array;


create array[length of array + 50 or so];


}





I'm sure there are better ways, but that's the best I could think of off-hand.
Reply:The other answerers are dangerously wrong. JordTeic's idea is inefficient (copy the array to a temp, and then delete and recreate array?).





Rjzii is just plain wrong (that's not how new and delete work, and that's not what your link suggests. Read it carefully).





CrazyCoder thinks C and C++ are the same. Wrong language.





%26gt; how can i increase the size of a dynamic array even though i dont know what its end size will be





Actually, you might not know the precise end size, but you can make an educated guess as to how big it needs to be in the short term right? One thing you could do is allocate a new array that is big enough, and copy the old array to the new array. Depending on what your array contains (complex objects for example), this could end up being an expensive operation.





A btree or linked list of buffers may be a better technique, depending on what your array contains and how it being used. Just link up arrays, and you can keep extending your “array”.
Reply:first of all you should include the header file %26lt;stdio.h%26gt;


there is a funtion named malloc you can use that function to allocate more memory to your array.





if you still have problem send me an email at mr_sheikhazad@yahoo.co.in

flash cards

Want help in c++ program?

Q.1 An election is contested by five candidates.The Candidates are numbered 1 to 5 %26amp; the voting is done by marking the candidates number on the ballot paper.Write a prog to read the ballots and count the votes cast for each candidate using an array variable count.In case a number read is outside the range 1 to 5,the ballot should be considered as a 'spoilt ballots' and the prog should also count the number of spoilt ballots.





Q.2 Write a function that creates a vector of user-given size M using new operator.

Want help in c++ program?
May be you can search at project assignment help website like http://askexpert.info/


Why should I use iterators rather than int for traversing through a list in C++.?

Why should I use


____________________


using namespace std;





vector%26lt;int%26gt; myIntVector;


vector%26lt;int%26gt;::iterator myIntVectorIterator;





// Add some elements to myIntVector


myIntVector.push_back(1);


myIntVector.push_back(4);


myIntVector.push_back(8);





for(myIntVectorIterator = myIntVector.begin();


myIntVectorIterator != myIntVector.end();


myIntVectorIterator++)


{


cout%26lt;%26lt;*myIntVectorIterator%26lt;%26lt;" ";


//Should output 1 4 8


}











Rather than


____________________





using namespace std;





vector%26lt;int%26gt; myIntVector;


// Add some elements to myIntVector


myIntVector.push_back(1);


myIntVector.push_back(4);


myIntVector.push_back(8);





for(int y=0; y%26lt;myIntVector.size(); y++)


{


cout%26lt;%26lt;myIntVector[y]%26lt;%26lt;" ";


//Should output 1 4 8


}

Why should I use iterators rather than int for traversing through a list in C++.?
Hi





well iterator have a main function, to access data from a container. when you have an stack, queue or some special container from STL you must use iterator to access the data inside those structure. It is impossible or very difficult to use other thing.





It is best practice to learn how to use iterator when you are dealing with complex data structures. Here i put some links.





good luck
Reply:safety, for one

flower girl

Need Help in making this c++ program?

Implement and thoroughly test a class named IVector that represents a


dynamic array of integers. It will have 3 private data members: int


capacity, int count, and int * items. The 'capacity' is the physical


size of the dynamic array (its actual number of elements). The 'count'


is the number of elements currently in use (indices 0, 1, ...,


count-1). The pointer 'items' points to the first element of the


dynamic array, which will be created by the operator 'new'.





Class IVector will have three constructors: 1) a default constructor


that creates an array of capacity = 2 and count = 0; 2) a constructor


with parameter int cap that creates an array of capacity = cap and


count = 0; and 3) a copy constructor with parameter "const IVector %26amp; V"


that creates an array that is identical to IVector V.





Class IVector will have the following public member functions: 1) two


getters that return the capacity and the count of an IVector object;


2) one declared "void Append( int item )" that adds 'item' to 'items'


at position 'count' and increments 'count' by one; 3) one declared


"void Insert( int index, int item ) "that adds 'item' to 'items' at


position 'index' and increments 'count' by one; and one declared "void


Delete( int index )" that deletes the item at position 'index' and


decrements 'count' by one.





Overload the operator '[ ]' to access elements of the vector by


subscript.

Need Help in making this c++ program?
Sounds pretty straightforward to me. So do you always get your homework done this way? Explains a lot about the state of the Software Industry.....
Reply:What is the question?
Reply:Does not look easy. May be you can contact a C++ expert at websites like http://askexpert.info/


Help: cal 3 - the cross product?

i have no idea how to do these:





1. let a = a_1i + a_2j and b = b_1i + b_2j be nonzero vectors in the xy plane. Show that a x b is parallel to k





2. show that (a x b) * b = 0 for all vectors a and b





3. let a, b and c be vectors. which of the following expressings make sense and which do not? explain you answer in each case.





a.) a * (b x c)


b.) a x (b * c)


c.) a * (b * c)


d.) a x (b x c)

Help: cal 3 - the cross product?
1 a and b are vectors in the x y plane because they have no k component. the cross product is a vector perpendicular to a and b so it must be parallel to k, You can also prove it by writing a and b with a zero k component and formally taking the Cross product.





2 axb is perpendicular to b and so dotted with b=0





3 b*c is not a vector but a scalar and a vectorX scalar does not make sense.


Programming in C++?

In the following code I am trying to resize the array at the correct place, my teacher said to use a temp variable and I can't figure this out. thanks.





while(!infile.eof())//this while loop resizes the vector and inputs the names from the file until the file ends


{//begin while


infile%26gt;%26gt;recordList[recordList.length()].... this!!!


int temp = recordList[recordList.length()].sku;


if(temp != infile.eof())//this if


{//begin if





infile.ignore(2,'\n');


getline(infile,recordList[recordList.len...


getline(infile,recordList[recordList.len...


infile%26gt;%26gt;recordList[recordList.length()]....


infile%26gt;%26gt;recordList[recordList.length()]....


recordList.resize(recordList.length() + 1);


}//end if


}//end while

Programming in C++?
Why do not you consult a C++ expert? Check http://k.aplis.net/
Reply:Seriously, ask on a forum. I've used this forum tons of times :





http://cboard.cprogramming.com/





You can get answers in like a couple of minutes. They're quite helpful, check the site out.





Like the other guy said, programmers don't usually lurk in Yahoo Answers. They spend their time in message boards, which is implied through the crazy fast replies.
Reply:This is not a good place to ask for C++ homework help. Your code is all truncated.





Find another forum.


When I compile my C++ code in linux, this error is printed: "no such file or directory",?

the error belongs to these lines:


#include %26lt;iostream%26gt;


using namespace std;


#include %26lt;vector%26gt;

When I compile my C++ code in linux, this error is printed: "no such file or directory",?
Maybe the setup your compiler is wrong.





patch up this codes, if you can run this then your compiler is working.





#include %26lt;iostream%26gt;


using namespace std;





int main()





{


cout %26lt;%26lt; "Hello World" %26lt;%26lt; endl;





return 0;





}





Note : your headers format is wrong, this the correct one.





#include %26lt;iostream%26gt;


#include %26lt;vector%26gt;





using namespace std; // always after all the headers otherwise you will use %26lt;vector.h%26gt; with "h" extension.
Reply:check to make sure you have those files. sometimes when folks build their linux box, the forget to install the headers for development. try doing a search for those files
Reply:check that all files and directories you are referrencing actually exist. I don't think vector is correct. read your documentation that came with the compiler.

curse of the golden flower

C++ dynamic array function help?

Write a program that will keep track of the enrollment of one class. Use a dynamic array to keep track of the enrollment. When enrolling a new student, the dynamic array will increase by one. You must use a function call to add student. I have been working on this problem all day and my code just does not work. My teacher said we do not need to use vector to increase the array size so any tips on how to solve this problem would be great because I just keep hitting a dead end.

C++ dynamic array function help?
C++ does not have any native "dynamic array" capability. The closest thing would be the use of the ANSI realloc() function, but that's a C thing, and not special to C++.


Now you *could* write your own class that manages an array. Let's say your class is something like this:





class Array {


a_class *m_array;


size_t m_nCurrentArraySize;


void Resize(size_t nNewSize);


...


};





Then your implementation might looks like this





void Array::Resize(size_t nNewSize) {


a_class *pNewArray = new a_class[nNewSize];


for (size_t i = 0; i %26lt; m_nCurrentArraySize; i++)


pNewArray[i] = m_array[i];


m_nCurrentArraySize = nNewSize;


delete [] m_array;


m_array = pNewArray;


}
Reply:You can use a linked list for this type of operation but your teacher wanted you to use 'dynamic' arrays. Nothing like making things more difficult.





one_student is assumed to be a structure.


student_class is assumed to be a dynamic array of one_student.





class MyClassArray


{


public:


MyClassArray() {student_enrol = NULL; student_count = 0;}


void AddStudent(one_student %26amp;student);


private:


typedef one_student *student_array;


student_array student_enrol;


int student_count;


...


};





MyClassArray::AddStudent(one_student %26amp;student)


{


student_class temp = new one_student[student_count+1];


for (int i = 0; i %26lt;= student_count; ++i)


temp[i] = student_enrol[i];


temp[student_count++] = student;


delete student_enrol;


student_enrol = temp;


}
Reply:It might be useful for you to paste the code you've got, and tell us specifically what error you're seeing.


C++ maxtrix?

I have to create a gradebook that reads in any amount of students and what their grades are. The user can add more to the matrix if they need another column of grades. I am having a problem with my addGrades function and need help on what is worng and how I can fix it. Here is the function for my "Add Grades" function:





void AddGrades(vector%26lt;String%26gt; %26amp;name, TTTBoard %26amp;Board)


{








int Row = Board.numrows() - 1;


int Col = Board.numcols() - 1;





//Board.resize(Col,Row);


//for(int j=0;j%26lt;= Col;j++){





for(int i = 0; i %26lt; Row; i++){


cout%26lt;%26lt;"Please enter a grade for "%26lt;%26lt;name[i]%26lt;%26lt;" ";


cin%26gt;%26gt;Board[Row][i]; //j,i ?


Row++;


}//end for





//}//end for











}//end fun.





//Thanks.

C++ maxtrix?
void AddGrades(vector%26lt;String%26gt; %26amp;name, TTTBoard %26amp;Board)


{


int Row = Board.numrows() - 1;





for(int i = 0; i %26lt; Row; i++){


cout%26lt;%26lt;"Please enter a grade for "%26lt;%26lt;Name[i]%26lt;%26lt;" ";


cin%26gt;%26gt;Board[i];


}//end for





}//end fun.
Reply:This if for a console app fight? Hence the cout statements? If so, the cin statement only needs to be seperated by commas.... and why are you using { instead of ; for the endings of a few of your lines of code?


C++ question please help.?

#include %26lt;string%26gt;


#include %26lt;vector%26gt;


#include %26lt;iostream%26gt;


#include %26lt;stdio.h%26gt;


//#include %26lt;ifstream%26gt;


using namespace std;








int main (int argc, char* argv[])


{





string fakefile;


cout %26lt;%26lt; "The file content is: ";


cin %26gt;%26gt; fakefile;


cout %26lt;%26lt; endl %26lt;%26lt; fakefile %26lt;%26lt; endl; //the body part


}





If I input "This is a string" for cin here, the output of the program is just "This". It seems that cin doesn't take space characters as part of the string, what can I do to solve the problem?

C++ question please help.?
See http://cppreference.com/cppstring/getlin...


Remarks:


1. #include %26lt;cstdio%26gt; , not #include %26lt;stdio.h%26gt; . Stdio.h is deprecated in modern C++.


2. To say that cin doesn't take spaces is misleading. cin is an object of istream, and it can definitely store spaces. It's the %26gt;%26gt; (extraction operator) that is in question here. It tries to extract everything into tokens (integers, strings, doubles, etc.). Whitespace is ignored. You can actually force %26gt;%26gt; to retain whitespace (see http://www.cplusplus.com/reference/iostr... ).


3. Don't post code directly here again. It's unreadable. Use http://www.rafb.net/paste/
Reply:you can use getline
Reply:try getline


C++ Program Help?

If you guys have been following my last questions you will see that I have learned alot but still need some help. I have finally gotten my program to work with the vector of structs. Now I need to be able to show the name(s) of the highest scorer(s) and the name(s) of the lowest scorer(s).





Here is my program thus far it is error free as of now.





// In a header file


#ifndef GRADES_H


#define GRADES_H





#include %26lt;iostream%26gt;


#include %26lt;string%26gt;





using namespace std;





struct Grades


{


string names;


int scores;


};





#endif

C++ Program Help?
You are progressing well. In order to print out the names with the highest and lowest scores, you will need to first sort the vector VGrade. That is one way of doing it - a way that uses the STL sort() function from algorithm.h file. But there are other ways. Since you want to know how to do it using the algorithm.h function, I will show you how to do that.





First of all, what you must understand is that the sort() function takes a vector's iterators and sorts all the elements within those iterators. So if you had a vector of integers v:





std::vector%26lt;int%26gt; v;





then you could call, after populating v with some values:





sort(v.begin(), v.end());





It would work. v will get sorted, and if you print out the 1st value of v, it will be the least value, and the last one will be the greatest value - thereby serving your purpose.





But in your case, it is slightly different because your vector is not of ints! Your vector is of GRADE-s, which is a "user defined datatype". So if you try to sort your vector, C++ will immediately ask you back - well, how do I know whether GRADE1 (an instance of GRADE) is %26gt; or %26lt; or = GRADE2?





Reason is simple: in order to sort, it needs to compare the values and determine which is higher and which is lower relative to the other values!





With ints, that was easy. C++ can tell whether 49 is greater than 72. But how will C++ tell whether GRADE1{Name:Koushik, Score:75} is greater than GRADE2{Name:John, Score:21}?





Therefore, first you need to provide the comparison operator less than (%26lt;) for your struct. Only one comparison operator is needed (you do not need to define "more than").





So go back to your code, and add this global function at the top (or in the header file):





bool operator%26lt;(const struct Grades%26amp; a, const struct Grades%26amp; b)


{


return a.scores %26lt; b.scores;


}





What this function does is it gives the compiler a way to tell which instance of a GRADES struct is higher and which is lower. And you just told it to use the "scores" field to decide that.





After doing that, just use the sort() method:





std::sort( VGrade.begin(), VGrade.end() );





After you do that, VGrade[0].scores is the lowest and VGrade[4].scores is the highest, and VGrade[0].names is the guy with the least score and VGrade[4].names is the guy with the highest score!

apricot

What do these do in c++?

char* tokenWords[55];


vector%26lt;string%26gt; table;


int j = 0; int k = 0;


string word; // One word per string





for(i = 0; i %26lt; 54; i++)


{


table.push_back(string(tokenWords[i]))...


}


--------------------------------------...


in tokenWords we have word.


and


----


for(j = 0; j %26lt; 54; j++)


for(i = 0; i %26lt; table.size() - 1; i++)


{


if(table[i] == table[i+1])


{


table.erase(table.begin() + i + 1);


}


}


esp the vector function.

What do these do in c++?
It looks like this code is making a list of all the words that were originally in tokenWords. It does this by putting all the words into a vector, and running through it 54 times, each time comparing every set of two words, and deleting the second one from the table vector if they are the same. After that function completes, "table" will contain a list of all words in tokenWords, in the order in which they occurred, with no duplicates.





P.S. This is not very efficient code.
Reply:It's code about a table class in a bunch of for loops...





j can't get bigger than 54, and i ends up building to that size...





meh I don't know what the code is for, drawing a table? lol


Those familiar with STL in C++ Please Help?

If you guys have been following my last questions you will see that I have learned alot but still need some help. I have finally gotten my program to work with the vector of structs. Now I need to be able to show the name(s) of the highest scorer(s) and the name(s) of the lowest scorer(s). The names and the scores are stored inside the vector%26lt;Grades%26gt; Grade; vector of structs so Grade[0].names = "Mike" and Grade[0].scores = 90








Here is my program thus far it is error free as of now.





// In a header file


#ifndef GRADES_H


#define GRADES_H





#include %26lt;iostream%26gt;


#include %26lt;string%26gt;





using namespace std;





struct Grades


{


string names;


int scores;


};





#endif

Those familiar with STL in C++ Please Help?
Do the for loop, but do the swap inside for the highest score.


Say


int hightest=0


int lowest = 1000


int position=-1;//used to hold position of highest





for (int count = 0; count %26lt;= 4; count++)


{


if(VGrade[count].scores %26gt; highest)//first one will be


{


position = count;


highest=VGrade[count].scores


}





}


Now you know the position of who has the highest and using position for name of highest (or lowest)
Reply:What's the question? By the way, the "Standard" Template Library is one of the main reasons why I don't think C++ is as beautiful as C. It seems there are as many different library implementations, and usages as there are companies willing to write compilers. Will your program work on every compiler, or just most of them?


Can someone please help me with my c++ program?

program needs to ask the user to input the num of numbers they want to store in a vector, %26amp; print out the smallest num, the largest, %26amp; the average. this is my code but i get vector subscript out of range %26amp; i dont know wat to do


#include %26lt;iostream%26gt;


#include %26lt;vector%26gt;


using namespace std;





int main ()


{


int numloop, value, small, large;


int sum=0;


double avg;


vector %26lt;int%26gt; vectorlist;





cout%26lt;%26lt;"Please enter the total number of numbers to be stored:"%26lt;%26lt;endl;


cin%26gt;%26gt;numloop;





for(int i=0; i%26lt;numloop; i++)


{


cout%26lt;%26lt;"Please enter value to be stored:"%26lt;%26lt;endl;


cin%26gt;%26gt;value;


vectorlist.push_back(value);


}





small=vectorlist[0];


for (int i=1; i%26lt;=numloop; i++)


{


if(small%26gt;vectorlist[i])


small=vectorlist[i];


}





large=vectorlist[0];


for(int i=1; i%26lt;=numloop; i++)


{


if(large%26lt;vectorlist[i])


large=vectorlist[i];


}





for(int i=0; i%26lt;numloop; i++)


{


sum+=vectorlist[i];


}


avg=sum/numloop;


cout%26lt;%26lt;"Smallest number:"%26lt;%26lt;small%26lt;%26lt;endl;


cout%26lt;%26lt;"Largest number:"%26lt;%26lt;large%26lt;%26lt;endl;


return 0;


}

Can someone please help me with my c++ program?
instead of writing all that. declare the vector AFTER you get input for how many numbers to use





ie





cout%26lt;%26lt;"Please enter the total number of numbers to be stored:"%26lt;%26lt;endl;


cin%26gt;%26gt;num;





edit: (been a while since C++)


vector %26lt;int%26gt;vectorlist(num); %26lt;- thats how it should look.





edit: also make sure you arent trying to acces part of a vector thats out of its bound. i had that mistake once where i had a loop start at 1 and not 0 but it ended 1 after the last spot in teh vector.





also you didnt declare i.








okokok i got it:


#include %26lt;iostream%26gt;


#include %26lt;vector%26gt;


using namespace std;





int main ()


{


int num, value, small, large, i;


int sum=0;


double avg;








cout%26lt;%26lt;"Please enter the total number of numbers to be stored:"%26lt;%26lt;endl;


cin%26gt;%26gt;num;





vector %26lt;int%26gt;vectorlist(num);





for (i = 0; i %26lt; num; i++)


{


cout %26lt;%26lt; "enter number" %26lt;%26lt; endl;


cin %26gt;%26gt; value;


vectorlist[i] = value;


}





small=vectorlist[0];


for (int i=0; i%26lt;num; i++)


{


if(small%26gt;vectorlist[i])


small=vectorlist[i];


}





large=vectorlist[0];


for(int i=0; i%26lt;num; i++)


{


if(large%26lt;vectorlist[i])


large=vectorlist[i];


}





for(int i=0; i%26lt;num; i++)


{


sum+=vectorlist[i];


}


avg=sum/num;


cout%26lt;%26lt;"Smallest number:"%26lt;%26lt;small%26lt;%26lt;endl;


cout%26lt;%26lt;"Largest number:"%26lt;%26lt;large%26lt;%26lt;endl;





system("PAUSE");


return 0;


}


Reading files in C++?

I have to read in some text files, and stores the data into a vector and matrix, and then writes the information in the vector and finds the average of the matrix in a new text file. I have no clue where to start, do you have any ideas of how to approach this problem? Thanks.

Reading files in C++?
#include %26lt;fstream%26gt;


............


using namespace std;





int main(){


........


//other defination





char *filename;


//the file name(path?) that u wanna read





ifstream instream;


//define a instream to let the file in





char buffer[1024];


//define a buffer to receive the context





instream.open(filename,ios::in);


//now open the file





filestream.read(buffin,sizeof(buffin));


//Read the context and store it into a buffer(an array in char)





........


//now u can do something to send the data in the array to the vector





//for more help and details u can find in MSDN Library


........


return 0;


}

song words

C programming HELP?!?

Can u solve this for me


1.Write a program which will read int vector (max leinght 100) and another int.Then the programm should show how many times, the int number will appear in the vector


PLZZZZ solve this 4 me :D

C programming HELP?!?
scanf("%d",%26amp;another_int);


if(a[i]==another_int)


count++
Reply:If you are too lazy to figure this homework assignment out (btw, it would take less than 12 lines of code to do), I am pretty sure you would be too lazy to log back on to YA, and give me 'best answer' if I spent the time to type it out.





So, no, you do your own homework assignment.
Reply:I agree with kenshin...





If you keep asking people to do things like these for you.... what's the point of going to School at all? You'll never learn like this. Might as well stop paying tuition fees and stay at home spamming lazy stuff here at Yahoo Answers.


C# "foreach" information?

i'm trying to write a collection array's string elementes longer than 4 in reverse order


foreach (string s in vector) if (s.Length %26gt; 4) Console.WriteLine(s);


worked great but i can't reverse it ... i tried with a normal for but then i can't test vector[i].Length because the object vector does not support Length ... so i'm looking for a way either to reverse my function's members so i can retest with foreach or for an opposite function of foreach

C# "foreach" information?
You could make you're collection inherit ienumerable. That way you can control how the collection is iterated through.





the foreach loop on its own does not give you this control.





The vector[i].ToString().Length should work just fine.


Although if you made your collection a generic of type string I do not believe you would not need to do this because the system would reccognize that the components of vector are a string and wouyld act upon them accordingly.
Reply:I think the only way you are going to be able to do this is to copy the elements into a separate array with each pass of the for...each loop, then go through the array in separate for loop by starting the loop at the (array.Length), then decrementing the counter (counter -= 1) to get the numbers in reverse order. There may be another way, but I don't think you will be able to do it solely through the for...each structure. Good luck : )


C++ question? Can you tell me why this isnt working?

As the title says:





void DisplayNamNum()


{


int test = Vector.size();





for(int i=0;i %26lt;= test; i++)


{


cout%26lt;%26lt; Vector[i].info %26lt;%26lt; "-" %26lt;%26lt; Vector[i].data %26lt;%26lt;endl;


}


MainMenu();


}





any thoughts as to why this gives me a runtime error?

C++ question? Can you tell me why this isnt working?
The array indexes run from 0 to size-1. Testing for i %26lt;= test will cause an out-of-bounds error on the last loop.





Change the test in the for statement to: i %26lt; test.
Reply:Based from the code, I think it would be much better to use Vector.at(i) instead of using Vector[i]. Also, if none of the answers here would help you, please post the WHOLE code.


Why doesn't this work in C++(gcc)?

std::vector%26lt;std::vector%26lt;std::vector%26lt;int%26gt; %26gt; %26gt; lookupTable(MAP_SIZE/GRID_SIZE, std::vector%26lt;std::vector%26lt;int%26gt; %26gt; (MAP_SIZE/GRID_SIZE, std::vector%26lt;int%26gt; (360,0)));








this gives an error:





globalData.h:41: error: expected identifier before numeric constant


globalData.h:41: error: expected ‘,’ or ‘...’ before numeric constant

Why doesn't this work in C++(gcc)?
i think u have to check all tha variable identifier


before those 2 statement..


i've noticed that these are constructor it require some identifier word in the top of programe . check it too


good luck

song titles

Please Help me out with this C++ problem ?

Hi i want to make a program using vector... but that is little bit hard for me to do because i have little knowledge about vector.. I know about string and using class. But the following functiion should be use with vector.. If anybody has any idea please responce. Im writting in details so that it makes clear.





1) bool update(const string%26amp; name, int teleNum, const vector%26lt;string%26gt;%26amp; nameList, vector%26lt;int%26gt;%26amp; teleNumList) : This function updates the telephone number of the person name to teleNum. The nameList and the teleNumList are the name list and the corresponding telephone number list. If it fails to find the person, it returns false otherwise it returns true.





bool erase(const string%26amp; name, vector%26lt;string%26gt;%26amp; nameList, vector%26lt;int%26gt;%26amp; teleNumList) : This function erases the person and the corresponding telephone number of the person name. The nameList and the teleNumList are the name list and the corresponding telephone number list. If it fails to find the person, return fals or els true

Please Help me out with this C++ problem ?
goto codeproject.com in c++ stl u will get help


C++ Program Question?

The question is:





Write a complete program that reads in some unknown number of positive integers from standard input (keyboard) into a vector. Then output all values to standard output (terminal) in reverse order (with one space between each value). The user will type a -1 to signal that they are through inputting positive integers. Do not output the -1.


For example, if the values read in are in this order: 1 3 5 2 9 then the output would be: 9 2 5 3 1


Do not output anything other than the values in the vector. In other words, do not prompt the user for input. Just assume the user knows to input some number of positive integers and a -1 to finish.





This is my code:





#include %26lt;vector%26gt;


#include %26lt;iostream%26gt;


using namespace std;





int main()


{


vector%26lt;double%26gt; Vec;


int vec_size = 0;


while (Vec[vec_val = -1)


{


cin %26gt;%26gt; Vec[vec_val];


vec_val ++;


}


for(vec_size; vec_size %26gt;= 0; vec_size--) cout %26lt;%26lt; Vec[vec_size] %26lt;%26lt; " ";


return 0;


}

C++ Program Question?
#include%26lt;vector%26gt;


#include%26lt;iostream%26gt;





using namespace std;


double val = 0;


vector%26lt;double%26gt; vec;


while(val != -1){





cin %26gt;%26gt; val;





vec.push_back(val);


};





int reverse_index = vec.size() -1;





vector%26lt;double%26gt; reverse(vec.size(), 0);





for(int i =0; i %26lt; vec.size(); ++i){





reverse[reverse_index--] = vec[i];





};





for(int i = 0; i %26lt; reverse.size(); ++i){





cout %26lt;%26lt; reverse[i];


};





return 0;





}











you don't even have to copy them if you don't want to you can just do








for(int i = vec.size() -1; i %26gt; 0; --i){





cout %26lt;%26lt; vec[i];





};














vectors have a bunch of built in functions such as size() push_back()....





check em out


http://www.cppreference.com/cppvector/in...


Please Help me out with this c++ problem if any body knows !!!?

Hi i want to make a program using vector... but that is little bit hard for me to do because i have little knowledge about vector.. I know about string and using class. But the following functiion should be use with vector.. If anybody has any idea please responce. Im writting in details so that it makes clear. th





1) void displayList(const vector%26lt;string%26gt;%26amp; nameList, const vector%26lt;int%26gt;%26amp; teleNumList) : This function displays the name and the corresponding number of all the persons in stored in nameList. The nameList contains the name list and teleNumList contains the corresponding telephone numbers. The pre-conditions are that both nameList and teleNumList have the same size and nth element of nameList corresponds to the nth element of teleNumList.





2)void append(const string%26amp; name, int teleNum, vector%26lt;string%26gt;%26amp; nameList, vector%26lt;int%26gt;%26amp; teleNumList) : This function appends the person name and the corresponding telephone number teleNum to the nameList and the teleNumList respectively.

Please Help me out with this c++ problem if any body knows !!!?
goto codeproject.com in c++ stl u will get help


C++ input file question?

I have a given text file that I need to read from with the following conditions:


First line contains names of N places


Each successive line contains a name of one of the places followed by an integer value, then the names of the places it is connected to and an integer distance





Here is an example file:





Miami Orlando Detroit Dallas


Miami 10 Orlando 5 Dallas 20


Orlando 8 Dallas 15 Detroit 40


Detroit 15 Dallas 50


Dallas 20 Miami 10 Orlando 15





First line lists the places...second line lists Miami, it's value of 10, it's connections to Orlando and Dallas and its distances to them (distance to Orlando is 5, distance to Dallas 20).





Basically, I need to read a file like this in and store it in a vector...The vector is of type pair%26lt;Node%26lt;T%26gt;*, int%26gt; where T is just a templated type, int is the distance. So each location in the vector will contain a Node which will just be the name of the place, and the distance as a pair.





How would I read these files in?

C++ input file question?
I would suggest you use the getline() function to read each line into a string, then parse the string. You can use eof() to detect the eof, but with the rules you stated, that is necessary only to check for the file NOT following the rules.





Hope this helps.

song downloads

How a c++ program which does the following?

1. Create a vector of size 1000 and have it store the values:


0.1,1.1,2.1,3.1,.....999.1





1.2 Truncate the vector of size of 5.





1.3 P:rint out how many values the vector is storing(use the vector itself to get this information).





1.4 Empty out the vector so that it stores NO values.

How a c++ program which does the following?
it is better to say:





DO MY HOMEWORK AND I DIDN'T SAY THANK YOU


Help me c++programme which does the following question?

1. create a vector of size 1000 and have it store the values:01.,1.1,2.1,3.1,.....999.1


2. Truncate the vector to a size of 5.


3. Print out how many values the vector is storing(use the vector itself to get this information)


4. Empty out the vector so that it stores NO values.

Help me c++programme which does the following question?
1.


1, 1.1, 2.1, 3.1,...99...


wtf kind of pattern is that?





2. how do u truncate a vector? u mean like free(%26amp;(vector+5)); ?





3. if u cant figure this out then thats just sad





4. huh? u mean like free(vector); ?


R&S Poll: What does "cloning" refer to?

When you hear someone mention "cloning", what comes to mind?





A.) making a duplicate of a person (or other animal)


B.) inserting a particular gene using expression vectors


C.) my mommy says science is the devil's work





Please include your religion, system of spirituality, (or lack of) when responding.

R%26amp;S Poll: What does "cloning" refer to?
It means doing this to you
Reply:A


but i don't see why would you clone a human
Reply:A - my wife did it all the time with yeast in her research.


Atheist.
Reply:I have to go ask my mommy what "gene" means
Reply:A! and of course....Attack of the Clones....hahaha...oh and Gladica!
Reply:A.) making a duplicate of a person (or other animal)





Atheist.
Reply:Neither. Cloning does not produce a 100% identical copy as in twins. In reality, it's a form of incest.
Reply:A). Atheist.
Reply:cloning is the forced splicing of DNA to produce a copy of the original source. The result is something that looks identical, but ages at double the rate.





Taoist, no real system.
Reply:I understand Eve was the first human clone.





Though how she ended up a different sex to the person she was cloned from I don't know.
Reply:cloning that comes to mind, hmm i'd have to say a duplicate of a person or animal.
Reply:a
Reply:Cloning refers to the exact copying of anything, be it animal, vegetable or mineral. So D. And I'm Wiccan.





Blessed be.
Reply:when someone copies your avatar and name. Ususally they say things you wouldnt say.
Reply:I suppose A sound closest. I and my denomination are opposed to cloning, but if people are cloned then they clones will need to place their faith in Jesus, just like we do.





Baptist.
Reply:the clones ... attack they will


use the force


C++ question?

How can I change the type of double in the vector class to the struct track from the following code


struct Track


{


string trackName;





int trackDuration;


};





class Vector


{


private:


double *array;


int num_elements;


int max;





// doubles the capacity of the vector by allocating a new array and copying


// all elements over to it


// used by the push_back function when the vector becomes full


void grow();





public:


// Constructors to initialize the vector's member variables





Vector() { max = 10; array = new double[max]; num_elements = 0; }


// default constructor





Vector(int, double);


// initialize all elements to a specific value





// destructor


~Vector() { delete[] array; }





// Copy Constructor -- Added 4/30/07


Vector(const Vector%26amp;);





// Assignment operator -- Added 4/30/07


Vector%26amp; operator=(const Vector%26amp;);





void push_back(double); //

C++ question?
Astronomy C/C++ source code





Last updated 5 January 2007





From time to time, I'm asked to provide source code for doing some sort of astronomical calculation, or for providing direct access to the numerous compressed datasets on the Guide CD-ROM. In the future, I intend to gather information about and links to all such source code on this page.





If you don't see what you want here, please ask. I've got a fair bit of source code not yet posted simply because I've not gotten around to documenting it thoroughly yet.





The source code in question is written in C; click here for info on source code in other languages, or here for info on other C/C++ source code for astronomy. I use an extension of .CPP just to force the compiler to do certain error checking (type casts, etc.) that C++ compilers do better than C compilers. The only use I make of C++ is in Windows user interface (MFC) code, and I haven't posted any of that yet. However, Mark Huss has produced a C++ implementation of much of this code, and you can click here to download the ZIPped C++ version (about 128 KBytes). If that link fails, try this one.





I will post remaining code here from time to time. If you have any priorities (bits you would really like to see soon), please let me know; I can probably rearrange the order to get your code uploaded faster.





Changes: Assorted changes have been made in the past with the regrettable absence of a change log. In the future, the .ZIP file will contain a CHANGES.TXT file, explaining what's different about the newly-posted files.





Porting: As much as possible, I've stuck with ANSI C. Most of the code has already been used in 32-bit DOS and Windows; some has even run in 16-bit DOS and Windows. A make file for Linux is provided, and the code works there (but I've only used it to create a Linux version of Find_Orb, and not much else.) Mark Huss' C++ version also compiles in Linux. The only warning I'd offer in this regard is that I haven't dealt with a "wrong-end" byte order platform yet, and I am quite certain that some of the code will crash in grisly fashion on such systems.





Documentation: Almost all the code has quite thorough descriptions of how the innards work. (This requirement is the main one slowing posting of code. Some source has been posted for Find_Orb and Charon. But most of it is complex enough that posting it without explanation would not be very helpful.)





Copyright restrictions: All this code is free for use in non-commercial applications. If you wish to use any of it in a commercial application, please let me know; I'm not averse to a little bartering in such cases.





There are two exceptions to this: the RealSky/DSS image extraction software and the FITS image compression software are entirely in the public domain. (Certain parts of the RealSky/DSS code came from the Space Telescope Science Institute (STScI), and the FITS compression software is a very slightly modified version of an STScI package.)





For all the source code, I would ask that you inform me of any bugs you find, and if you make interesting improvements, I'd very much like to hear about them.





Astronomy source code in other languages (so far, only Java): Personally, I haven't written much of anything in a language other than C or C++ since 1988. (Not a good thing, I realize.) I get occasional questions about source code in Java and Pascal (surprisingly, not in BASIC... though you can click here for a list of BASIC programs from Sky %26amp; Telescope.)





In addition to his C++ astronomy source code, Mark Huss has written a lot of astronomy source code in Java, and has updated and improved it a bit recently (March 2002) as described in the following e-mail:





hi Bill,





I finally got things organized - the updated library, source, and info is


now available on my website: http://mhuss.com/AstroLib.html.





javadoc is an amazing thing - take a glance at


http://mhuss.com/AstroLib/docs/api/index...





regards,





--mark huss





(And from a previous e-mail...)





This is what's currently running the lunar phase info and 'darkest hours'


page on the DVAA website (http://dvaa.org). You should know, however, that I


used Meeus 'mystic formulas' instead of applying your 'witness the truth


thereof' philosophy in a couple of places for expediency ;-).





regards,





--mark





Some other implementation of assorted astronomical algorithms in C/C++: Mark Huss has written quite a bit of astronomy-related code in C++. P. J. Naughter has implemented much of Meeus' Astronomical Algorithms (second edition) in C++. You can click here for his code and info about it.





Source code for accessing Guide datasets and orbital elements: There is rather a lot of code in this category, and it has its own separate page. Click here for information on this subject. There are also some pieces of code to access some large catalogues here.





Source code for accessing JPL's DE ephemerides: This has grown to the point where it needed a page of its own. Click here for C/C++ source code for accessing JPL DE ephemerides.





Source code for RealSky/DSS image extraction: This is the same library used in Guide for image extraction; it's also used in version of SkyMap Pro, and, I suspect, in some other commercial astronomy software. You can read about it and download it from this page.





Source code for FITS image compression: A very slightly modified version of an STScI program. Click here for information and source code.





Source code and a DOS executable for tables of Galilean satellite events: This is the code I used to generate the lists of occultations, eclipses, transits, and shadow events shown in Guide. Click here for an example of the output of this program. The code is quite ugly, and I don't recommend its use very highly. Click here to download the source code and .EXE files (about 69 KBytes).





Source code for basic astronomical calculations: This file will eventually encompass all the low-level routines I use in Guide: nutation, aberration, computing planet positions from VSOP and PS_1996, refraction, lunar positions, the orientations of planets, coordinate systems, sidereal time...





At present, it has many of these, but not all. Here's a summary of the purpose of most of the .CPP files:





Click here to download the ZIPped code (about 93 KBytes). Here's some discussion of the meaning of the various source files supplied:





ALT_AZ.CPP: Code to convert RA/dec to alt/az, and galactic coordinates to RA/dec.





ASTEPHEM.CPP: The main function for the code to compute asteroid ephemerides. It demonstrates accessing orbital elements from the Guide disk, and then shows how to compute an RA/dec, magnitude, elongation, and other data based on using those elements to compute the asteroid position, and VSOP to compute the Earth's position. The most significant thing omitted right now is the topocentric offset.





ASTFUNCS.CPP: Some basic functions to set up asteroid/comet elements and to compute their locations (solving Kepler's equation and so forth.)





The Kepler's equation solution draws quite a bit of interest, so much so that there is a separate page discussing Kepler's Equation.





BIG_VSOP.CPP: Code to compute planetary positions from the full VSOP series, which is stored in binary form on the Guide CD-ROM. The logic is very similar to that used for the "truncated" VSOP (see VSOPSON.CPP), except that the function works by reading in pieces of a file; VSOPSON.CPP assumes the data file has been read into memory.





CLASSEL.CPP: Takes a state vector (position and velocity) and computes the "classical elements" (semimajor axis, eccentricity, mean anomaly, argument of perihelion, etc.) Currently, the FIND_ORB orbit determination software and the integrat numerical integration program make use of this; after computing an orbit in vector format, they use this routine to produce something in a form suitable for human consumption.





COLORS.CPP and COLORS2.CPP: Given, say, a B-V color value, it's possible to compute a "pretty good" V-R value. Similar conversions are possible between most other color indices, with varying degrees of accuracy. The general form is a polynomial, say,





index2 = a0 + a1 * index + a2 * index2 + a3 * index3 +....


These resemble Taylor series, though I suspect they are actually curve-fit polynomials. I got them from some Fortran snippets supplied by Brian Skiff, and they have been converted to C here.





Certain conversions are handled by inverting the polynomial. The need to do this indicates a very unreliable color conversion, to be used only in cases of dire emergency.





Also, code to convert Tycho B and V to Johnson B and V is given, along with a little piece of test code. (That Tycho-to-Johnson algorithm is one based the book that was distributed with the Hipparcos data, "Introduction and Guide to the Data." COLORS2.CPP is a more recent, and probably better, Tycho-to-Johnson piece of source code.)





COM_FILE.CPP: This is pretty much Guide-specific code. Guide goes through some odd hoops to draw comets as speedily as possible. One headache it has to deal with is that there isn't any consolidated set of comet orbital elements, the way there is with asteroids (e.g., MPCORB or the Lowell Observatory ASTORB). Instead, it has to dynamically combine "current comet" data from MPC with a list of historical comet data. The confused nature of comet designations makes that a pain (it's not always easy to match comets from one list with those from another). Also, Guide uses some pregenerated data to omit comets that are too faint to be of interest over a desired time span... all nifty stuff, and it helps Guide to run somewhat more briskly. But it's probably not of interest to most people.





COSPAR.CPP: Code to compute the "planet orientation" matrix for the Sun, all planets, and quite a few satellites. A few years ago, the IAU set up a committee to define pole positions and longitude systems for these objects. The pole position is usually defined to be a linear function in RA/dec, with the meridian intersecting the J2000 plane as another linear function. Often, some small trig terms are added to those linear functions.





At present, COSPAR.CPP includes many, but not all, of the satellites shown by Guide. Some (such as the "captured asteroids" of gas giants) have no defined orientations. Others (small inner objects such as Amalthea) just haven't been tackled by me yet (no big job to do, but not much interest, either).





DATE.CPP: Source code for the following calendrical systems: Julian, Gregorian, Hebrew, Persian (Jalaali and 'Modern Persian'), Islamic, and Chinese, and French Republican. Basically, you can do conversions between JD and the calendar systems.





DELTA_T.CPP: Code to compute Delta_T = TD - UT for any date, using a lookup table for years 1620 to 2002 and extrapolations beyond those ranges.





DE_PLAN.CPP: Code to compute very precise planetary positions using the PS-1996 series of Chapront. Includes Mercury through Pluto. To use this, you'll need to download this file of coefficients.





DIST_PA.CPP: Code to compute the distance and position angle between two spherical coordinates. Theoretically, this ought to be a straightforward task. In practice, there are an amazing number of ways to get roundoff/truncation errors and divides by zero, mostly involving how you deal with cases where the distance between the two points is small. I am reasonably sure now that this code evades all such cases.





EART2000.CPP: Code to compute the Earth's location relative to the Sun, in J2000 coordinates, using VSOP.





EASTER.CPP: Code to figure out the date of Easter for a given (Gregorian) year.





ELP82DAT.CPP: Code to compute the position of the moon using the ELP-82 (Ephemerides Lunaire Parisienne 1982) theory of Chapront and Chapront-Touzé. To make use of this code, you'll need to download this file of coefficients.





GETPLANE.CPP: Code to compute the location of any planet, or the Moon, relative to the Sun. The resulting vector is given in five different systems.





JD.CPP: Produces an "example" program showing the use of the functions in DATE.CPP. You can type in, say, "jd 10 7 1999", and be told what day 10 July 1999 corresponds to in assorted calendars. (You can also get the actual JD corresponding to that date, or type in, say, "JD 2451324.879" and get the calendar date... which was the original reason I wrote the program.)





JSATS.CPP: Code to compute the positions of the Galilean satellites, using Lieske's theory as given in Meeus' Astronomical Algorithms. Quite a few smaller terms are omitted.





LUNAR2.CPP: Code to compute the position of the moon, using the truncated series from Meeus' Astronomical Algorithms. This uses the same data file (VSOP.BIN) as the VSOPSON.CPP code discussed below.





MISCELL.CPP: Code for basic matrix functions (inverting an orthogonal matrix, rotation, setting identity matrices, etc.) Also code to handle the odd system used for variable star designations, and to provide a version of the C-language ctime() function that takes a JD and can work over a full time range (ctime only works between 1970 and 2028.) Also, this version gives plenty of formatting options (two-digit vs. four-digit years, DMY vs MDY vs YMD, months shown as digits, time shown in decimal hours/decimal minutes/decimal seconds/decimal days, etc.)





NUTATION.CPP: Computes the nutation of the earth's equator.





OBLIQUIT.CPP: Computes the obliquity of the earth's equator for dates from -8000 to +12000.





PERSIAN.CPP: Very special-purpose code, written to demonstrate how the Persian calendar is computed. Most people will either skip this, or just use the functions in DATE.CPP without really needing to know how the functions were put together.





PLUTO.CPP: Code to compute the position of Pluto, using the series given in Meeus' Astronomical Algorithms. This uses the same data file (VSOP.BIN) as the VSOPSON.CPP code discussed below.





PRECESS.CPP: Code to build the matrix used to convert coordinates between epochs, plus code to use those matrices to convert vectors, RA/dec coordinates, and ecliptic coordinates between epochs.





REFRACT.CPP: Contains functions to convert an observed altitude (one affected by refraction) to a true altitude (one that would be seen on an airless planet), or vice versa. Two different methods are provided. (See next paragraph for a third method.)





REFRACT4.CPP: Contains a more complex/sophisticated method of computing refraction, as given in the Explanatory Supplement to the Astronomical Almanac . This one does a numerical integration through the atmosphere, including effects due to observer altitude, temperature, barometric pressure, humidity, and wavelength of light being refracted. (But the end result is usually not all that different from that given by the two methods in the previous paragraph, except for very low altitudes or extreme conditions.)





RELATIVI.CPP: Code to test out the precession of Mercury's orbit due to general relativity, and also to test a quick and easy way to include first-order general relativity in orbit computations. The code may also be of interest because it integrates using the method of Encke, with a pretty good Runge-Kutta numerical integrator. Unfortunately, it could stand some documenting...





ROCKS.CPP: Code to compute positions for 25 faint, inner satellites of the gas giants. These are all modelled as precessing ellipses.





SHOWELEM.CPP: Code to take a set of orbital elements, and produce a human-readable text version, mostly resembling the MPC's "standard" eight-line format.





SSATS.CPP: Code to compute the positions of eight of Saturn's satellites (Mimas, Enceladus, Tethys, Dione, Rhea, Titan, Hyperion, Japetus), using the theory due to G. Dourneau.





VISLIMIT.CPP: This code computes the limiting visual magnitude, sky brightness, and extinction coefficients. It's basically lifted/ported from Brad Schaefer's article and code on pages 57-60, May 1998 Sky %26amp; Telescope, "To the Visual Limits".





VSOPSON.CPP: Code to compute planetary positions from a truncated VSOP series. That series is stored in binary form on the Guide CD-ROM, and you have to load it into a buffer to use this function. The logic is very similar to that used for the full VSOP (see BIGVSOP.CPP), except that that function works by reading in the file of coefficients on an "as needed" basis. This function (and several others listed on this page) require that you download this file of coefficient data.








Code to access astronomical datasets





UCAC-2 access: Significant enough that there is a separate page for the UCAC-2 code.





CMC-14 access: Significant enough that there is a separate page for the CMC-14 code.





Ax.0 access: Source code described and provided here.





USNO-B1.0 access: Some not well-documented (but probably still helpful) code to access USNO-B1.0 in its "original" 80GByte form is available here.





Tycho-2 CD access: Given the delays in getting Guide 8 out the door, I've had requests to provide some means of accessing the Tycho-2 CD-ROMs. (These disks have the additional advantage of being free, provided by ESA and USNO. Click here for details. Though I wouldn't be surprised if they're running low on disks.)





While I haven't done much with this data (except process it for use in Guide 8, of course), I have written a small utility to access Tycho-2 data for a given star. Click here to download the DOS software, source code, and documentation. Given this, you can extract positions, proper motion, and magnitudes (both Tycho and Johnson), with error estimates, for a given Tycho-2 star. (Both the transformation to the Johnson system and the error estimates are important. "Raw" Tycho mags match Johnson magnitudes only in a loose manner, and the Tycho-2 magnitude data runs the full range from extremely accurate to moderately accurate... you _must_ check error estimates to determine which is which.)





Artificial satellites: This has grown to the point where it deserved a page of its own. Click here for details on C/C++ code to compute artificial satellite ephemerides. (The currently-posted version is a nice improvement over some older artificial satellite code I posted previously. I'm leaving the old stuff because it's still getting a little use here and there.)





Symplectic integration: This single source file is derived from code posted by David Whysong on the newsgroup sci.astro.amateur. I simplified the code a bit and added a "test code" main() function. You can now get the results of our collaboration at David's Web site. It's a very interesting way of doing numerical integration, on several counts.





The major use for it is in cases where one wants to maintain certain constants of motion (total energy, angular momentum, etc.) Usual methods of numerical integration (Runge-Kutta, Adams-Bashforth, etc.) don't necessarily do a good job of this over really long integration spans. This was the reason for David's interest in the method. He is a graduate student working on globular cluster simulations. If, say, the total energy of his simulated globular increased (or decreased) over billions of years, we may assume that the whole thing would mysteriously explode with stars flying everywhere (or collapse down to a black hole). More details are given in the source code.





DIST.CPP: This code resulted from a discussion on the newsgroup sci.astro.amateur about how to compute the geodetic distance between two lat/lon points on the earth's surface. It incorporates two methods: one assumes a spherical earth, the other (much more complex) uses a method from





PAGE2.CPP: This code can take an RA/dec position and figure out the corresponding pages to be used in the Millennium Star Atlas, Uranometria, and Sky Atlas 2000. There's also a little snippet that takes a (lunar) lat/lon and figures out the corresponding page to be used from Antonín Rükl's Atlas of the Moon.





Source code for Charon: I've started the process of turning the Charon astrometry software into an open-source program. This begins by posting the source code for Charon (about 84 KBytes). You will also need the basic astronomical source code discussed above.





Why the source for Charon is being posted


Current state of the Charon source code


Overall structure of Charon


Why the source for Charon is being posted: I do not now, nor have I ever, regarded astrometry software as a commercially profitable idea. By a slight margin, I'm able to keep myself fed and indoors through sales of Guide; trying to sell Charon is not apt to help very much. By posting it, I hope to accomplish the following:





-- People will be able to improve/modify the source code to accomplish tasks of their own. (The basic idea behind almost all open source, of course.) With any luck, some of that code will return to me and I'll post it here for others to use. I know that some people have written Charon-like code and functions for their own project; I'm hoping that we can stop re-inventing wheels.





-- The number of users of Charon has risen to the point where I'm not doing too well at keeping up with requests for improvement. I've become a bottleneck to progress.





-- Posting the source code will probably encourage somebody to start work on making a version of Charon that does not require a Guide CD. If it can access catalog data from the Internet, then it would require no CD-ROM at all. In this case, people could do astrometry with Totally Free Software. This might encourage some people to enter the hobby.





-- Verifying the fact that the code does what I tell people it does becomes easier. Some people build their own astrometry software because they would rather not have to place trust in me and my software. Such trust would be well-placed, especially since the results of the software have been examined by dozens if not hundreds of people. (The worst risk in 'rolling your own' astrometry software is that it will usually be tested only by you, and not by dozens if not hundreds of people.) But being able to check the source code ought to relieve some anxieties.





Current state of the Charon source code: All of the rest of the source posted on this site has been cleaned up nicely and documented well enough to make it useful to somebody. Right now, this is not in the least true of Charon. You can use the source to satisfy curiosity about parts of Charon, and maybe to grab bits and pieces from the code. But there are some things I need to do to make it usable.





Charon is compiled with WATCOM C/C++, the only compiler I've got that can produce 32-bit DOS code that can access graphics. (Micro$oft's compiler can produce 32-bit DOS console applications, but none that access graphics.) I'm in the process of getting the make file into a usable form; right now, it runs across assorted directories and is not 'ready to go out of the box'.





There are parts of the code that run for hundreds of lines without the faintest trace of the residue of a comment. The code isn't particularly ugly (except for the enormous main() and parts of matcher.cpp), but figuring out what does what is a frightening prospect right now.





Overall structure of Charon: The program is overdue to be broken up into certain components. To a minor extent, this breakup is present now, but it's incomplete and Charon is really one big monolith at heart. This is really a shame, because astrometry software lends itself naturally to being broken into a set of component tasks.





Breaking Charon into components would make following the structure of the code much easier. It would let us rip out certain parts, replace them, or use them by themselves. The components (or, if you prefer, "near-components") are:





(1) Load an image from a file


(2) Find and build a list of stars in an image


(3) Get the RA/dec of an object at a given time


(4) Get stars from a catalog within a given radius of a given RA/dec


(5) Pattern-match the list of image stars to the list of catalog stars


(6) Display the results and interact with user


(7) Assorted minor functions


(8) (FUTURE, not yet implemented) Automated object detection


Load an image from a file: A piece that loads an image, be it FITS, SBIG, or other, into a standardized in-memory format. This is currently done using the load_image() function in load_img.cpp. A side note: it's possible that, in preference to writing one function that can load a zillion image formats, there should be a separate routine that can convert a zillion image formats into FITS. If I had it to do over again, I'd do it that way.





Find and build a list of stars in an image: Takes an image in the aforementioned standardized in-memory format and return a list of stars in it, with their pixel coordinates and brightnesses. The code in findstar.cpp does this right now. (I'm not totally thrilled with the job it does on noisy images; it often finds hordes of spurious stars in noise. Ideally, the code I wrote might get pitched in favor of SExtractor. I started playing with SExtractor and gave up, though; I had no real success in puzzling out what was supposed to do what.)





Get the RA/dec of an object at a given time: Given an object ID such as "V4191 Sgr" or "P/Linear S4" or "1997 XF11", and a date/time and observer position, this figures out the RA/dec of that object. The code in find_obj.cpp does this right now. If somebody tells Charon, for example, "Here's an image of asteroid 4179", Charon can figure out a rough RA/dec for 4179 at the time the image was taken, so it knows where to look for a pattern match.





In some ways, this is just a convenience. People can and do feed Charon images and just say, "Here's an image taken at about 14h51m12s, +10 43' 56"... go process it." But the 'convenience' is a major one.





Get stars from a catalog within a given radius of a given RA/dec: Given a catalog name and an RA/dec (normally provided by the preceding piece, but not always) and a radius, this piece grabs catalog data for that area and returns it in a standard way. Right now, assorted functions in grab_gsc.cpp do that. They can extract ACT, GSC, or GSC-ACT data from the Guide disks, or USNO Ax.0 or SAx.0 data from the CDs distributed by USNO, or GSC 1.2 data from the files that come from the STScI server. All the functions feed through the grab_catalog_stars() function in charon.cpp.





For Guide users, this is pretty nice; it means they can get all the data they need (comet/asteroid orbits, plus the GSC, plus other handy catalogs) all on one disk. For an open-source project, though, it'll be nice if the 'catalog grabbing' code can 'grab' from the two GSC CD-ROMs distributed by STScI, or via Internet. The first, at least, ought to be very straightforward. The second will be slightly trickier, but opens the program to anyone connected to the Internet... this would be a huge plus. I note that VizieR, for example, provides a way to ask for a given list of data from a catalog, specified by RA/dec and radius, using a single URL... almost exactly what we'd need for a stunt like this.





Right now, people have to shell out some money to buy the Guide disk, or the two GSC disks, to get into astrometry. Neither is really pricey, as astronomy products go ($89 and $69, respectively). But if trying out astrometry software was totally free, it might draw in some fresh blood.





Pattern-match the list of image stars to the list of catalog stars: Given a list of image stars (probably from the 'get stars from image' component), and a list of catalog stars (probably from the 'get stars from catalog' component), this part does the automated pattern-matching required to say, "Use the following transformation to go from image to RA/dec space and vice versa." The code for this is currently in matcher.cpp, and is a horror to behold... it's the sort of neighborhood where programmers only go in pairs.





Display the results and interact with user: This piece takes the image, lists of image stars and catalog stars, and transformation, and display the whole mess on the device of your choice. At present, this is done partly with code in the main( ) of charon.cpp, with a big chunk of it in dispimg.cpp and smaller pieces throughout the code. When applied to multiple images, this could allow for blinking. (The current blinking scheme in Charon is considerably less logical. I'd ignore it if possible.) This piece is intimately hooked into the entire user interface problem of how people can click on the image and manipulate it on-screen.





The previous components could be written in totally 'clean', generic ANSI source. Porting them to other OSes would be relatively straightforward. Unfortunately, the 'display/interact' component will be messy, heavily OS-dependent code.





Assorted minor functions: A whole slew of small pieces to do things such as write out MPC headers and reports, figure out which image star or catalog star is nearest to a given cursor position, provide ways to adjust settings, handle the list of MPC stations...





(FUTURE, not yet implemented) Automated object detection: Once the pattern matching code has done its work for a particular image, we can get a list of the RA/dec/magnitude values in that image. (Such lists would have value in and of themselves, of course.) Then we can take two or three such lists at different instants, and look for moving objects.

sending flowers