Alex Edwards 321 Posting Shark

So if I don't want to pass &cPtr, what reference do I want to pass?

No you do, that is correct.

I thought you were planning on directly using your Globally defined pointer (the one that was mentioned in one of your posts quite some time ago) as part of your class.

My apologies for the confusion.

Alex Edwards 321 Posting Shark

This is where I am now... And I have no idea how to do the other things :/

#include <iostream>
using namespace std;

int main()
{
  array rectNum; //most likely an error - not sure if there's an array type/object predefined in C/C++
  int N;
  cout << "How many rectangles do you want to input data for?";
  cin >> N;
  
  if(n<0 && n>5) cout <<"error";
  else //error, below code will most likely run no matter what N is, use blocks
  
  for(int i = 0; i < N; i ++)
    cout << rectNum[i].getArea()  << endl;
  
  for(int i = 0; i < N; i ++) 
    cout << "Enter the x1 value for rectangle " << i << ".";
    cin >> //error, nothing to input into
    cout << "Enter the y1 value for rectangle " << i << "."; //error, i doesnt exist, for loop reaches 1st line only
}

You have quite a few errors you'll be marked down for, and you still didn't answer my question.

Alex Edwards 321 Posting Shark

I'm really thankful but I have only two values for each rectangle.

I'm guessing each Rectangle is defined by a Point class/struct correct? Or are they just integral/floating types (int, double, unsigned int... etc).

You're not giving much information.

Alex Edwards 321 Posting Shark

In your example, what is the difference between setCharacter() and &GetCharacter() functions? In my current code I have setCharacter

void Item::setCharacter(Character &cPtr){
	invoker= &cPtr;}

But I'm not really sure what to do with getCharacter

Edit: I just remembered, I have my object Player being pointed at by a global pointer, not really sure how that changes anything

You want your classes to be generalized so that in the event that you add more players, the functionality of the classes wont change much.

Having handled data within the class via containment (or composition) is a much better approach.

The reason you have your global pointer is to (currently) reference the only character you're going to use. Your classes should be made adaptable so that a change outside of the classes will not change the functionality inside your classes.

Alex Edwards 321 Posting Shark

I understand you but now I have 20 minutes left and if I don't pass this exam I'll have to do the test in september and I can't do it then. So if you could just write the program and I'll come to understand it later while I'm at home.

Thanks,
Hristian

I promised I wouldn't provide coded answers for people anymore. Here's the area in point-form.

(x2 - x1) * (y2 - y1) = area

where x2 is the second coordinates x value, and x1 is the first. The difference makes the width.

y2 is the second coordinates y value and y1 is the first. The difference makes the length.

Multiplying these two components makes the area.

All you have to do is find a way to snag each respectable point and code it. You'll also have to iterate through N rectangles and show their areas.

for(int i = 0; i < N; i ++)
    cout << rectNum[i].getArea()  << endl;

Where rectNum is an array of rectangles and getArea() is a method that calculates the area of the rectangle using the method mentioned above.

You can do this in less than 20 minutes.

Alex Edwards 321 Posting Shark

Well the problem is that I perfectly understand what I have to do but I have absolutely no idea how to do it.. And I'm now on my Term Exam so I kind of need it now and I'll understand the way it's done later. It's just that it's my last chance now :/

Cheers,
Hristian

Ok, so how is it done? I can step you through the coding.

Alex Edwards 321 Posting Shark

I've already read a bit about vectors, and it seemed like the way to go. Then my functions would display all the items in the vector, allow you to select which item you want to use, and that selection would call the proper item use function

You seem to know what you're doing, but I'll leave this chunk of code to be helpful to you for future pointer and reference usage --

#include <cstdlib>
#include <iostream>

using namespace std;

int *a, b;
void setInt(int& x)
{
     a = &x;
}

int main(int argc, char *argv[])
{
    b = 2;
    
    setInt(b); //sending reference of b as argument
    
    //referenced pointer a should now point to the address of b
    
    *a = 5; //assigning the value 5 to the address pointed by the dereferenced pointer
    
    cout << *a << " " << b << endl; //notice both have the same value, although I never directly assigned b with 5
    
    //pretend b is the private Character variable that I want to access and a is the pointer referencing the
    //address of b. Now we can control b by using the pointer a.
    
    cin.get();
    return 0;
}
Alex Edwards 321 Posting Shark

Really thanks for the fast reply but I don't actually know anything about this part of the programming. So could you write the program if you can :/

Thanks,
Hristian

Normally I wouldn't mind providing big hints for a project like this, but honestly the answer is right in front of you.

Before even thinking about programming, think of how the solution is obtained.

Also, try to make an attempt to write the code. You might actually get it.

Alex Edwards 321 Posting Shark

Hi guys,

I need to write a program in C++ that will input data for N rectangles (0<N<5). The data for each rectangle consists of coordinates of the lower left and upper right corners, which are positive integers, less than 100.
Then I need it to calculate the area of each rectangle.

Thanks,
Hristian

Think of how area is calculated.

In order to obtain the area of a rectangle, you only need to know the length and width of the rectangle. The area is--

length * width

--which is the easy part. Now, the question becomes "how do I obtain the length and width of the rectangle by only knowing the lower left and upper right corners?"

Draw two points and list their coordinates (give them fake ones if you want) then think of how you can come up with a length and width for a rectangle that would fit those coordinates.

William Hemsworth commented: I dont know how you put up with him :P +2
Alex Edwards 321 Posting Shark

What's up with the Item *items and then later setItems(Item *theitem)

Item *items simply states that I have a private pointer variable named items. It's a declaration.

setItems(Item *theItem) allows an assignment of multiple items to the private variable items.

For example, suppose I wanted to move all of the items from a storage box to the characters inventory. I can simply use a pointer (or array) as a storage value argument and assign a copy of the address to the private-scoped variable items. items would then point to all of the values accessible by the storage pointer.

That can be fairly complicated though, and unwanted. Unfortunately a pointer's job is simply to do what it says - point to an address of something for access. If you were to do multiple assignments, like--

items = storage; //assuming storage is a pointer (or array) to items within the storage
items = bag; //assuming bag is a different array of items

--the pointer would no longer be pointing to the address of storage, but instead the address of bag.

This will be inconvenient if you want to store many different item objects. It might be more reasonable to use a container, such as a vector, to store said items.

Actually, the items pointer can be replaced with a vector that holds items--

vector<Item> items; //stores many individual items - like a resizable array

--where you won't have to understand memory management via …

Alex Edwards 321 Posting Shark

I think I get what's going on now. getCharacter(). #1 is saying "use the character that is being referenced by the function", with the .setHP being the call for the member function. Then getCharacter() #2 is doing the same thing as the first, and getHP is taking the value of the characters HP and adding 20 to it.

Exactly.

However, you should set some bounds in your Character::setHP(int amount) method.

For example--

void setHP(int amount)
{
   if(amount >= 0) //if hp is being increased...
   {
      if((getMaxHP() - getHP()) >= amount) //if amount added to current hp doesn't exceed maxHP...
      {
              setHP(amount + getHP());
      }
      else if((getMaxHP() - getHP()) < amount) //if amount added is too much, just set to maxHP..
      {
              setHP(getMaxHP());
      }
   }
   else
   {
      //code for when character receives damage...
   }

}
Alex Edwards 321 Posting Shark

That's severely odd... it worked now. Thanks a million!

Alex Edwards 321 Posting Shark

I'm still confused as to what exactly &getCharacter and SetCharacter(Character &c) are doing. It's one of the things I read about but still don't quite understand.

One last edit should make things clear, since I didn't take into account that we need a way to properly retrieve the Character object being set.

class Character
{
     private:
                 Item *items; //resembles a character capable of having many items                 
                 
                 //private stats variables...
     public:
                Character(/*code for stats...*/){/*constructor code...*/};
                void setItems(Item *theItems); //sets the items
                Item getItem(); //returns a copy of the item, not a reference
                void selectItem(int n); //selects the nth item from the list
                void useItem(); //use the currently selected item
                void selAndUse(int n); //selects an item and immediately uses it
};

//Chances are the above code would be applicable mainly for useable items--

struct Item //most likely a Useable item
{
      private:
                 Character *invoker; //a pointer, EDIT
      public:
                Item();
                virtual void use() = 0; //pure virtual function, no general Item can be created
                                                //unless it extends this class and overrides this function
                void setCharacter(Character &c); //sets the character to access when use is invoked
       protected:
                Character &getCharacter();//returns a reference to the character, but only for derived Items //EDIT
};

//more code...

This is going to be fairly difficult to explain, so please bare with me.

When you create an item, you want it to have some kind of Character to associate with when it is used.

This concept is fine, but when we do this--

void setCharacter(Character &c)

Alex Edwards 321 Posting Shark

As far as abstraction goes, I think I get the gist of it, as well as overriding functions/virtual functions/purely virtual functions.

The thing that you're doing that I read about but never actually understood how/why you would do it is use an Object for a function call. Such as

void setCharacter(Character &c); //sets the character to access when use is invoked
Character getCharacter();//returns a copy (not reference) of the character

Another thing: if all the use item functions are member functions of my Character class, then how do I use those functions with the item objects that will eventually be created?

Simply invoke the use command the each Useable item should have.

The Character should be aware of the item they have selected and aware that the item does something when used.

The items should be responsible for the actions it takes, not the Character.

The pure virtual function in the Item class will become inherited from members that extend from the Item class--

struct Hi_Potion : public Item
{
       
         void use()
         {
               //increase the HP of the character by 20
               getCharacter().setHP((getCharacter().getHP() + 20));
               (*this).~Hi_Potion(); //invoke the destructor of this object
         }

};

--Fixed, sorry.

Alex Edwards 321 Posting Shark

While we're semi on the topic, could someone please tell me what the difference between if{, else if{ and else{ is?

if(<condition>)
{
   //do something
}
else if(<other possible condition>)
{
  //do something else
}
else <if above conditions fail, then resort to this condition>
{
    //last resort if other conditions fail
}

else and else if can only be used immediately after an if.

if's can exist on their own, for example--

if(<condition>)
{
   //do something
}

if(<another condition>)
{
   /do something
}

--in which, neither if relies on each other. Basically both conditions can be executed if both are true, unlike the if-else statements above where only one of the conditions will be true.

Alex Edwards 321 Posting Shark

I think the easiest thing to do would be to have my Character class directly affected by the items that you're using. So when you equip an item, it increases the strength in your Character class, or when you use a potion it directly increases your health.

The only thing I'm wondering is if this violates the principals of OO programming by having outside functions determining the values of my character's stats within it's own separate class. If it does, I'm going to have to reconsider how my functions are going to indirectly affect your stats without changing them.

You can have relationships between classes. That's perfectly fine in the OO sense.

Obviously the relationship between a Character and the item is such that--

A Character can have many items.
An item can effect a character (or multiple characters, depending on the item).

--

class Character
{
     private:
                 Item *items; //resembles a character capable of having many items                 
                 
                 //private stats variables...
     public:
                Character(/*code for stats...*/){/*constructor code...*/};
                void setItems(Item *theItems); //sets the items
                Item getItem(); //returns a copy of the item, not a reference
                void selectItem(int n); //selects the nth item from the list
                void useItem(); //use the currently selected item
                void selAndUse(int n); //selects an item and immediately uses it
};

//Chances are the above code would be applicable mainly for useable items--

struct Item //most likely a Useable item
{
      private:
                 Character invoker;
      public:
                Item();
                virtual void use() = 0; //pure virtual function, no …
Alex Edwards 321 Posting Shark
if (num1 <= num2)
cout << num1 << "is less than or equal to" << num/*error here*/ << endl

Change that to num2 and I think you won't get any more errors.

Alex Edwards 321 Posting Shark

A blue passenger train moves southwards at a speed of 80km/hr. Unfortunately as it enters a junction it collides with a brown goods train moving northwards. The collision happened 30 minutes after the goods train takes off. Use C++ to illustrate the above.

You will most likely want to print the coordinates of both the train and the brown goods train every minute or second, and display their speed as well.

Alex Edwards 321 Posting Shark

This is actually a much harder task than you think.

I, myself, have tried to make games. Sure some worked but when it came to upgrading them (implementing new features, etc) it became problematic because so many of my functions relied on each other.

What you want to do is generalize how the items and the Characters will interact. You're on the right track for determining how to separate your items in terms of classes, but what role will they play?

Will items be responsible for their own behavior, or will the character determine the behavior of the items?

For example, when you use a potion, will the potion access a member of the Character and increase/decrease said stats, or will the character activate a potion and perform actions based on the supposed effect of the potion?

These are fairly deep topics of design patterns for complex programs. Making an RPG can be incredibly difficult if the design is done improperly.

I don't mean to sound discouraging, but if you have some kind of stopping point or limit for your RPG then what you're doing is perfectly fine. If you plan on building up on this RPG, though, you will encounter a fair amount of issues as you decide how the program will be structured.

Alex Edwards 321 Posting Shark

Pretty much worked straight away for me. All I did was create a new project, delete the default package and copy in your package instead. DoodleBug.java was missing a package statement, but that was all...

You still having issues?

Can't yet because I'm copying NetBeans IDE to my iPod so I can take it with me wherever I go.

Once that's done I'll give it a shot.

Alex Edwards 321 Posting Shark

Here's the code that I wanted to add to the project. It's in zip format to make things easier--

Alex Edwards 321 Posting Shark

Ok that idea worked, but now I'm getting an issue with compiling. It says it cant find the files even through they're in the same package.

I've even tried adding the "package <packagename>" statement at the very top of the java files, but to no avail. What am I doing wrong?

Alex Edwards 321 Posting Shark

You want to add a library, or just source files to edit? If it is a library (.jar) or something, there should be an add external library option. But I think you want to add source files, you can just drag-drop or do it directly in the filesystem.

I created a package in my project manager and then tried opening a file to examine.

From there I tried clicking and holding the tab that had the class information and when i try to drop the file into the package it shows the NOT circle symbol. When I release the mouse, obviously nothing happens.

I found out that you can control the directory that the package is created in so I guess I'll try the second option and simply add the files directly to the package.

Alex Edwards 321 Posting Shark

I'm a complete rookie with NetBeans, and that's unfortunate because this summer our Instructor wants us to use NetBeans throughout the entire course.

I'd just like to know... how do I add existing files to a project? I've tried right-clicking the project folders to see if there was some kind of add command. There were none, but then I simply tried creating a package to hold the projects and still no add project command. Not even in the File option or anywhere else.

It's not that I'm lazy and don't feel like finding the existing project/package in the source files, but I find it somewhat inconvenient to not be able to easily implement classes into one package or project in a Development Kit like NetBeans.

Is there any way to do what I'm asking, or am I SOL and must simply create a shortcut to the sourcefile folder where the projects and packages are located?

Alex Edwards 321 Posting Shark

hi Zyaday,
using setBounds() method
first set the layout of panel as none.
syntax:

button_name.setBounds(int x,int y,int width,int height);

example:

JB_ClickMe.setBounds(20,25,150,20);

You could resort to absolute positioning, but in the event that the Panel is resized you may want to use a layout.

I'd suggest looking up the following in google--

Java class LayoutManager

--LayoutManager is really an interface, not a class... but nonetheless it will show you the multiple types of Layout Classes that implement the interface and will help you determine how you want your buttons to look on your Panel.

Jishnu commented: Good help done :) +3
Alex Edwards 321 Posting Shark

Hello, i'm using a Jpanel, I am using an image as background . On top of that i want to put buttons on it. The problem is I cannot repostion the buttons? can anyone help me here!!??

There's no reason to be shy. Post your code so we can help you out.

Alex Edwards 321 Posting Shark

In your example, both T and int are const expressions. (T).name() is not a const because it is only known at runtime.

Ok, now that was a very straightforward response. Thanks a million.

Alex Edwards 321 Posting Shark

The condition must be satisfied before compile time, not during runtime. So what you are attempting to do on line 15 is just not possible because those variables are not known until runtime.

The type T itself is known before runtime, is it not? For example, if I instantiate said class with a parameter, the compiler will replace any occurance of T with the actual type, for the particular class/function.

I used the statement-- #if (T == int) --and the compiler didn't choke up on me.

I did some research and the #if directive states that the expression must be a constant expression. What exactly does that mean? I'm still having trouble understanding that.

Note: The above statement seems to always be true, even though I'm not really sure how the == operand is resolving the expression above.

Alex Edwards 321 Posting Shark

The problem resides below - I'm trying to make a directive command that disable one constructor definition, or the other, based on the parameter of T. When I uncomment the block around the if statement, I get this error-- ... missing binary operator before token "(" --but when I replace the ( typeid(T).name() == typeid(int).name() ) statement with something like 0 or true the code compiles just fine. Here's the code--

#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

template<class T>class Enum;

template<class T>
class Enum
{ 
    public:
           struct Case;
/*
#if ( typeid(T).name() == typeid(int).name() )
#define CONSTRUCTOR
           Enum(){};
#else
#define CONSTRUCTOR
           Enum(){};
#endif*/

    private:
            Case *cases;

};

template<class T>
struct Enum<T>::Case
{
    T value;
    string name;
    static int total;

    Case(T theValue, const char *theName)
    : value(theValue), name(theName) {total++;};
};

template<>
struct Enum<int>::Case
{
    int value;
    string name;
    static int total;

    Case(const char *theName)
    : value(total), name(theName) {total++;};
};


int main(int argc, char *argv[])
{
    
    cout << ( typeid(int).name() == typeid(int).name() ) << endl;
    cin.get();
    return 0;
}

As you can see, I tested the statement in main and it works perfectly fine, returning a bool value after the comparison. I just don't understand why #if doesn't recognize it as a bool expression.

Alex Edwards 321 Posting Shark
Alex Edwards 321 Posting Shark

I believe you got to declare what today is.

He already did.

I believe this is one of the reasons I like Java's enumeration-class better than C++'s enumeration type.

You can't convert an int into an enum, unfortunately.

Alex Edwards 321 Posting Shark

I need to write these three functions to convert strings into integers:

int dectoint( string st ); // e.g. "14" → 14
int hextoint( string st ); // e.g. "14" → 20
int bintoint( string st ); // e.g. "10" → 2

and these three functions to convert integers into strings:

string inttodec( int n ); // e.g. 14 → "14"
string inttohex( int n ); // e.g. 20 → "14"
string inttobin( int n ); // e.g. 2 → "10"

Again, Im confused by this as well.

Think about what the words hexadecimal, decimal a binary mean.

Binary means base 2, so you never reach 2 and the way numbers are read in binary are--

2^2, 2^(n-1), 2^(n-2)... 2^(0)

--in terms of place-values, much like the decimal system--

10^n, 10^(n-1)... 10^(0)--

--where 10^0 is the ones place. The same applies to hexidecimal except that after 9 you use ABCDEF to express the digit--

G^n, G^(n-1)... G^(0) --

Note that in all of the above cases, for each system, you never reach the number that represents the place value. In Binary, you never reach 2, in Decimal you never reach 10 and in Hexidecimal you never reach G.

Use this to your advantage. For example, the modulus operator give you a remainder of a number based on the divider, for example

23%10, 54%10, 11%10 --

or any number %10 will return a remainder between 0 and …

Alex Edwards 321 Posting Shark

Note: This isn't my code, but something I found in one of the WinAPI tutorials on a forum.

#include <windows.h>
#include <cstdio>
#include <iostream>
#include <cstdlib>


//This will clear the console.
void ClearConsole()
{
     //Get the handle to the current output buffer...
     HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
     //This is used to reset the carat/cursor to the top left.
     COORD coord = {0, 0};
     //A return value... indicating how many chars were written
     //   not used but we need to capture this since it will be
     //   written anyway (passing NULL causes an access violation).
     DWORD count;
     //This is a structure containing all of the console info
     // it is used here to find the size of the console.
     CONSOLE_SCREEN_BUFFER_INFO csbi;
     //Here we will set the current color
     if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
     {
          //This fills the buffer with a given character (in this case 32=space).
          FillConsoleOutputCharacter(hStdOut, (TCHAR) 32, csbi.dwSize.X * csbi.dwSize.Y, coord, &count);
          FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
          //This will set our cursor position for the next print statement.
          SetConsoleCursorPosition(hStdOut, coord);
     }
     return;
}
Alex Edwards 321 Posting Shark

Can any one please assist with code for two objects coming from different direction. Subsequently, collide after intersection. The objects should be moving at 80km/h. And collision should happen shortly 30 minutes after take off

This sounds like a physics problem with elements of-

Newton's Law
Conservation of Momentum
(Possible) Conservation of Energy

-You will most definitely need Conservation of Momentum since during the collision, there's no telling how much energy is lost from heat due to air resistance/crumpling. The first two laws should be a good start.

Also, what is the angle of misdirection? I have a program that can solve these kinds of problems but its written in Java.

Alex Edwards 321 Posting Shark

Hi,

I'm having a problem understanding this thing.
Suppose I have a function that returns a generic value.
Inside I have "try" and "catch" statements for exceptions.
Now once those exceptions have been detected, what and I mean in the name of Jesus butt-hole is my function suppose to return?

In my case I have a "clip" (first in last out) made out of templates.
I load it with pointers and then "eject". Once my clip is empty and I try to eject it, obviously that should considered as an exception. The problem is I do get the "failure" message as instructed but right after, the compiler crashes.

If anyone could shed some light on this, it'd be much appreciated.
Thank you.

If your "clip" is a stack, why not make it so the eject returns a pointer to NULL when the list is empty?

T remove()
{  
   T *temp = 0;
   if(size > 0)
   {
      //code to remove and return T 
   }
   else
        return *temp;
}
Alex Edwards 321 Posting Shark

OH! I get it now! What it's doing is it's going through all the elements in the array, and checking each of their coordinates against the current coordinates. It increments to move onto the next object in the array, and if none of them match, the loop breaks and it returns to the top. =)

Does that mean that I need to change the value of LOCATIONS to however many special squares I want? Like for different towns, etc.

Yes and as you do you'd, of course, have to create more location-structs to do so. Furthermore, you'll want to give each a unique string name.

After that you'll have to add additional conditions in your doSomething() method. If needed you can rename it then go to the for loop with loc in your movement-for-loop and change the name of that method to whatever you change doSomething() to.

I wasn't being at all creative, I just wanted it to make sense.

Alex Edwards 321 Posting Shark

Yep, it does, thank you. As far as I'm concerned there's no way in HELL I would have come up with that on my own.

Again though the one thing I'm trying to puzzle out the specifics of:

for(int i = 0; i < LOCATIONS; i++)
         {
          if(loc[i].x == currentX && loc[i].y == currentY)
          	loc[i].doSomething();
          }

The reasons I'm confused are the i < LOCATIONS and the loc stuff. What part of the array is loc accessing? Where do you get the value for LOCATIONS? And why does i even need to be incremented? Sorry to ask the same general question as before, I just want to make sure I'm actually understanding this.

Remember, LOCATIONS is a macro that is defined by the preprocessor definition #define LOCATIONS 2 so any time the compiler sees LOCATIONS it really is 2.

The loc variable is the array defined here--

Location loc[] = { Inn, Start};

--and Inn is located at indice 0 of the array and Start is at indice 1.

Notice that although the size of the array is 2, we never get to 2. The reason is because of how elements are accessed in the array. You can only access from 0- to- (n-1) indices where n is the size.

In the for loop, I'm iterating through the loc array by incrementing i.--

for(int i = 0; i < LOCATIONS; i++)
       	      {
          		if(loc[i].x == currentX && loc[i].y == currentY)
          		loc[i].doSomething();
              }

--if I didn't increment i, …

Alex Edwards 321 Posting Shark
#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

	typedef struct SomeStruct
	{
		
        private:
        	string name;
  		
    
   	    public:
       	    int x, y;
       	    SomeStruct(const char *arg, int xLoc, int yLoc) : name(arg), x(xLoc), y(yLoc){}
	
       void doSomething(){
       		if(name== "ok"){
       			cout<<"Okay!";}
       		else if(name== "inn"){
       			cout<<"You're at an inn." << endl;}
   			else if(name== "start"){
   			 	cout<<"Start!" << endl;}
      			
    			
	    }
}Location;

#ifndef LOCATIONS
#define LOCATIONS 2
#endif

Location Inn("inn", 2, 4), Start("start", 0, 4);

Location loc[] = { Inn, Start};



int main()
{
    int currentX= 2, currentY=4; //placed the coordinates outside of the for loop block
	for(;;)
	{
    	
    	
    		
      
      
      int direction;
      		cout<<"What direction do you want to go?";
   			cin>> direction;
   			
   			switch(direction)
            {
   				case 1:
   					if(currentX == 10){
   						cout<<"\nYou cannot go any farther that that direction."<< endl;
   						break;}
					else{
        			currentX++; //changed
   					cout<<"\nYour coordinates are " << currentX <<"," << currentY <<"." << endl;
        			break;
 					}
 					
 				 case 2:
      				if(currentX ==1)
                    {
          				cout<<"\nYou cannot go any farther in that direction."<< endl;
          				break;
                    }
      				else
                    {
     					currentX--;//changed
     					cout<<"\nYour coordinates are " << currentX <<"," << currentY <<"." << endl;
        				break;
                    }
  				case 3:
					if(currentY== 10)
                    {
						cout<<"\nYou cannot go any farther that that direction."<< endl;
   						break;
                    }
					else
                    {
        			    currentY++;//changed
   					   cout<<"\nYour coordinates are " << currentX <<"," << currentY <<"." << endl;
        			    break;
                    }
        			
     			case 4:
					if(currentY==1)
                    {
						cout<<"\nYou cannot go any farther that that direction."<< endl;
   						break;
                    }
					else
                    {
        			   currentY--;//changed
	                   cout<<"\nYour coordinates are " << currentX <<"," << currentY <<"." << endl;
        			   break;
                    }
          
            
              
                  }
        
              for(int i = 0; i < LOCATIONS; i++)
       	      {
          		if(loc[i].x == currentX && loc[i].y == …
Alex Edwards 321 Posting Shark

This seems to work well so far--

#include <iostream>
using namespace std;

template <class T>
class list
{
	public:
		list();
		list(int);
		void insert(T);
		void remove();
		bool empty();
		void print();
		~list();

	private:	
		int size;	
		T *thelist;	
		int numinlist;	
		int newsize;
};

template <class T> list<T>::list() : size(5),newsize (size)		
{	
	thelist = new T[list::size];	
	numinlist=0;	
}

template <class T> list<T>::list(int in_size): size(in_size), newsize(size)	
{
	thelist = new T[in_size];
	numinlist=0;
}

template <class T> void list<T>::insert(T write)
{
	if(numinlist < list::size)
	{
		thelist[numinlist] = write;
		numinlist++;
		cout << "Number of items in the list is now"  << "  " << numinlist << endl;		
		cout << thelist[numinlist - 1] << " " << (numinlist - 1) << endl;
	}
	else
	{
		T *temp = new T[newsize];			//make new pointer temp
		for (int i = 0; i < newsize; i++)	//copy list to new pointer		
			{				
				temp[i] = thelist[i];                            
			}
			delete[] thelist;				//delete old pointer the list

		newsize++;							//increment size

		thelist = new T[newsize];		//make new pointer the list		
		for (int i = 0; i < (newsize-1); i++)	//copy temp to new pointer
			{
				thelist[i]= temp[i];
			}
			delete [] temp;					//delete temp

		thelist[newsize-1] = write;			
		numinlist++;
		cout << "Number of items in the list is now" << "  " << numinlist << endl;	
	}
}


template <class T> void list<T>::remove()	
{
         
	if(numinlist > 0)
	{
		T *temp = new T[newsize];			
		for (int i = 0; i < newsize; i++)		
			{				
			     temp[i] = thelist[i];                            
			}
			delete[] thelist;				

		newsize--;

		thelist = new T[newsize];			
		for (int i …
Alex Edwards 321 Posting Shark

Something like this for the removal code?

T *temp = new T[newsize];			
		for (int i = 0; i < newsize; i--)		
			{				
			temp[i] = thelist[i];                            
			}
			delete[] thelist;				

		newsize--;

		T *thelist = new T[newsize]; //error	
		for (int i = 0; i < (newsize-1); i--)	
			{
			     thelist[i]= temp[i];
			}
			delete [] temp;								
		numinlist--;
		cout << "Number of items in the list is now" << "  " << numinlist << endl;

Ok I think I found another error

In your remove you declare thelist as a local variable which masks the real value of thelist.

Alex Edwards 321 Posting Shark

Wow, I actually understood the majority of that code.

Things I didn't:

#
}Location;

#ifndef LOCATIONS
#define LOCATIONS 2
#endif

This part: Why do you have Location; outside the SomeStruct braces? Also the #indef part, I've seen it before but I'm not entirely sure what it means.

Also the part within the for loop. I think I understand the part within the if braces, but I just don't understand the increment part in the for arguments.

SomeStruct is just a typedef for objects of its kind. It's like how int is a type-definition for ints.

When you say int x, you are declaring that x is a reference-variable for int objects (well, to an extent. ints are really primitive types and not objects, but they have good enough similarities for this example). The same applies for Location - it's just a shorter, and a more understandable name for "SomeStruct" and performs the same way a SomeStruct object would.

The preprocessor directives are pretty self explanatory. You can define a macro with a value or with actual code or anything and anytime your project is built/compiled and that exact word is found in the code, it will replace the word with the code/value that it is associated with. Example...

#define DBL double

DBL x = 2.2;

Whats really happening is DBL is being replaced by the keyword double during compile time, and it is interpreted like this-- double x = 2.2; #ifndef means "If not defined, then..." - basically …

Alex Edwards 321 Posting Shark

I only made a small change - its commented in the code below--

#include <iostream>
using namespace std;

template <class T>
class list
{
	public:
		list();
		list(int);
		void insert(T);
		void remove();
		bool empty();
		void print();
		~list();

	private:	
		int size;	
		T *thelist;	
		int numinlist;	
		int newsize;
};

template <class T> list<T>::list() : size(5),newsize (size)		
{	
	thelist = new T[list::size];	
	numinlist=0;	
}

template <class T> list<T>::list(int in_size): size(in_size), newsize(size)	
{
	thelist = new T[in_size];
	numinlist=0;
}

template <class T> void list<T>::insert(T write)
{
	if(numinlist < list::size)
	{
		thelist[numinlist] = write;
		numinlist++;
		cout << "Number of items in the list is now"  << "  " << numinlist << endl;		
		cout << thelist[numinlist - 1] << " " << (numinlist - 1) << endl;
	}     //^^ above, changed it so it displayed the number that was just entered
	else
	{
		T *temp = new T[newsize];			//make new pointer temp
		for (int i = 0; i < newsize; i++)	//copy list to new pointer		
			{				
				temp[i] = thelist[i];                            
			}
			delete[] thelist;				//delete old pointer the list

		newsize++;							//increment size

		T *thelist = new T[newsize];		//make new pointer the list		
		for (int i = 0; i < (newsize-1); i++)	//copy temp to new pointer
			{
				thelist[i]= temp[i];
			}
			delete [] temp;					//delete temp

		thelist[newsize-1] = write;			
		numinlist++;
		cout << "Number of items in the list is now" << "  " << numinlist << endl;	
	}
}


template <class T> void list<T>::remove()	
{
	if(numinlist > 0)
	{
		numinlist--;
		cout << "Number of items in the list …
Alex Edwards 321 Posting Shark

Can you post what you have currently? I'm not getting the same error somehow.

Alex Edwards 321 Posting Shark

Consider the following code, where I store created Location objects in an array then reference each of them. Notice the new name-parameter I gave them. This will help reduce the amount of code you write in your movement loop, but it will increase the code in your Location structs--

#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

typedef struct SomeStruct
{ 
       private:
              string name;
               
       public:
              int x, y;
              
              SomeStruct(const char *arg, int xLoc, int yLoc)
              : name(arg), x(xLoc), y(yLoc){}
              
              void doSomething()
              {
                   if(name == "ok")
                   {
                          cout << "Ok!" << endl;         
                   }
                   else if(name == "inn")
                   {
                          cout << "I'm an inn!" << endl;
                   }
                   else if(name == "start")
                   {
                          cout << "Starting!" << endl;
                   }
                   /*
                   else if...
                   */
                   else//final case
                   {
                        
                   }
                  
              }
}Location;

#ifndef LOCATIONS
#define LOCATIONS 2
#endif

Location Inn("inn", 2, 4), Start("start", 0, 4); 

Location loc[] = {  Inn,  Start  };


int main(int argc, char *argv[])
{
     int currentX = 2, currentY = 4; //notice that these are the inn's cooridnates

     //inside your movement-loop...

     for(int i = 0; i < LOCATIONS; i++)
     {
           if(loc[i].x == currentX && loc[i].y == currentY)
              loc[i].doSomething();
     }
     
    
     cin.get();
     return 0;
}

--There's also another way of doing this, but it involves mid-first-quarter C++ knowledge.

Ellisande commented: Had to wait 24 hours +1
Alex Edwards 321 Posting Shark

So that's the easy way. Is there a better, more efficient way, or is this what would actually be accepted as good coding?

There is, and I've been working on a good example for some time now.

Alex Edwards 321 Posting Shark

Now the problem I'm having is how do I use a struct like Location Inn like you described above to give you different options depending on your location in the grid? I'm able to move around my grid from 1-10 in both the x/y directions, but that's all I've got so far.

You should have an if statement that takes into account many cases while you are moving (I'm assuming you're moving in a loop).

while(true /*or whichever condition you use to keep movement going*/)
{
       //...
       if(currentX == Start.x && currentY == Start.y)
       {
               //do something
       }       


       //...

}

Assuming that you want to do it the fairly easy way.

Alex Edwards 321 Posting Shark

Sorry I had that added for debugging purposes =P

Alex Edwards 321 Posting Shark
#include <iostream>

using namespace std;

	typedef struct Location
	{
		int x, y;
  		Location(int col, int row) : x(col), y(row){}
	};

Location Start(2,2);

int main(){
    cout<< Location.start;
	cin.get();
	}

I'm doing something wrong =\

Location is just a typedef for Locations. You can use the word Location to create coordinate objects, for example--

Location Inn(3, 4); //creates a location struct named Inn with x set to 3 and y to 4

Furthermore, the variable/function "start" doesn't exist in Location, and you cannot call Location in that way since its just a definition for anything that is that type.

In your above example, Start IS a location struct, so you can call upon its coordinates in this way--

cout << Start.x << ", " << Start.y << endl;
Alex Edwards 321 Posting Shark

I think its because you assigned memory to a local-scoped T pointer in both constructors and not the actual variable in the private declaration. The local T must have masked the private T.

template <class T> list<T>::list() : size(5), newsize(size)		//default
{
	thelist = new T[list<T>::size]; //used to be T *thelist = new T[5]
	numinlist=0;
}

template <class T> list<T>::list(int in_size) : size(in_size), newsize(size)		
{
	thelist = new T[in_size]; //same here
	numinlist=0;
}
Alex Edwards 321 Posting Shark

Okay, I think I get it now, the only question I have is what does the : x(col), y(row) - on part mean?

Pre-initialization - because the assignment operator causes a copy of the object to be made during the assignment, which can cause the program to do more work than it should.

Pre-initializing is considered good programming practice.