Alex Edwards 321 Posting Shark

Here's how the skeleton of my program looks.

public class ClassThreaded extends Thread {
	public static void main(String[] args) {
		for(int i = 0; i < 2; i++) {
			new ClassThreaded().start();        
		}
	}
  
	public void run() {
		startDetaching ();             
	}
    
	private void startDetaching () {  
		SELECT .... FROM mytable WHERE activityid IN (select ids from another_table)

		while (colllection.next()) {
			// This will update only one record.
			"UPDATE ... WHERE ...;
		}
	}
}

So, in this case, is there a possibility that both threads will try to update the same record? or will it work at all?

Please advise...


Thanks

You will most likely be updating the same fields, despite the fact that you're creating an instance of 2 threads, since they're of the same class.

Like previously stated, try to make an array with the Table's ID's known ahead of time and the make an array that holds arrays (a double array, or list) and section off your ID's in separate arrays.

For example, Tables 1000-2000 will be in one array, 2000-3000 in another... 3000-4000 in another, so on and so forth.

From there, upon creation of your class, have a static number increment upon creation--

static int creationValue = 0;
int classNumber = 0;

//in constructor

class MyThread()
{

       classNumber = creationValue;
       creationValue++;

}

public int getNumber()
{

      return classNumber;

}

and when you need to get a value, you will have an array of arrays defined already, all you need to do …

Alex Edwards 321 Posting Shark

You could also create multiple timers and register an action listener on your class.

The Timer object is meant to activate the action listener of the class in the specified milliseconds.

So you can have one actionlistener and multiple timers with different commands.

About your question of whether you need an array or not... I really doubt you should need your array if, for example, you are directly copying and pasting a table of section A to another table of section A for example. If you're going to be placing values in the exact same section of another table, there should be no reason for additional work of storing values that will be in similar locations.

If you have a way to access the section in your table (for example, by name or number) and the names of the first table are the same as the second, then I suppose you could store - in advance - the names for the table the thread will allocate its next value to then iterate through the names and repeat the process.

I haven't played around with the callable interface that Ezzaral suggested, but I doubt he'd give you any bad advice. My first bet would be to keep a list of references to your table (divided into different array, equal to the amount of threads you want to use) then have each thread iterate through each section.

Note: I suppose you could implement the callable interface …

Alex Edwards 321 Posting Shark

I have a program with a bunch of threads running. I kill them all at the end of the program. I have stepped through and seen them all abort. Is there a way to see (since I cant when stepping through) which thread it is? I can see the process in my task manager, anyway to get more info on it? Thanks.

Can't you make each thread do something (like every second) and watch them die?

For example, print a number onto the console screen?

Alex Edwards 321 Posting Shark

Here's an example of something I have been testing without good results--

import java.util.regex.*;
import java.util.*;
import java.io.*;
import java.io.Console;

public class Equation_Solver{
	private static String temp, bS = "\\";
	private static ArrayList<Character> myChars;

	public static void main(String[] args) throws Exception{


		/*
		Console console = System.console();
		if (console == null) {
			System.err.println("No console.");
			System.exit(1);
		}
		while (true) {
			Pattern pattern =
			Pattern.compile(console.readLine("%nEnter your regex: "));
			Matcher matcher =
			pattern.matcher(console.readLine("Enter input string to search: "));
			boolean found = false;
			while (matcher.find()) {
					console.format("I found the text \"%s\" starting at " +
				   "index %d and ending at index %d.%n",
				matcher.group(), matcher.start(), matcher.end());
			found = true;
			}
			if(!found){
				console.format("No match found.%n");
			}
		}*/


	//	Pattern p = Pattern.compile("((A(B(C))))");
	//	Matcher m = p.matcher("ABC");

	//	System.out.println(m.groupCount());
	//	System.out.println(m.group(4));
	//	System.out.println(m.matches());
	//	System.out.println(m.group());

	//	String temp = "A    B C".replace(" ", "");
	//	System.out.println(temp);


			//Perform Calculation in order of operations (PEMDAS)
			temp = "(5 + 7*3*(x^2-9))".replace(" ", "");//changes the equation into a compressed String
			myChars = new ArrayList<Character>(0);

			for(char element : temp.toCharArray())
				if(element != '(' && element != ')') //places the values without paranthesis in the arraylist
					myChars.add(new Character(element));

			char otherChars[] = new char[myChars.size()]; //creating an array to hold the Char objects as primitive types

			for(int i = 0; i < otherChars.length; i++)
				otherChars[i] = (char)myChars.get(i); //cast the char objects into char primitive types


			Pattern p = Pattern.compile(temp);//takes our temp value with paranthesis and stores it in a Pattern
			String temp2 = String.valueOf(otherChars);
			System.out.println(temp2);
			temp2 = temp2.replace(" ", "");
			temp2 = temp2.replace("+", "\\+"); // …
Alex Edwards 321 Posting Shark

A Hashmap is basically a combination of an array and a list:

Suppose you had a whole bunch of keys. The way a hashmap works is basically, you reduce the keys mod some fairly large prime number (say n). The prime number is essentially the "verticle" size of the hashmap (this is the way I picture it). What I mean by verticle is that, you create an array of size n, and this array has n indices.

So now you have this n element array, where the indices hold elements placed according to their keys mod n. As a (simple) example, let element A have key = 1, and element B have key = 2. Let n = 3. Reducing 1 and 2 (mod 3), we obtain 1 and 2, respectively. So element A will be stored at array index 1, and element B at inex 2. Fairly straight forward.

But what happens when two keys mod n have the same result? For example, suppose element A has key = 5 and element B has key = 8, and n = 3 (just as an example, the keys/n will generally be larger). Then 5 ~ 2 (mod 3) and 8 ~ 2 (mod 3) ("~" means congruent, I don't know how to do a triple-bar equal sign). So we have a collision. That is, to store element A and B, we reduce them mod 3, but in both cases we get a result of 2. So technically both A and …

Alex Edwards 321 Posting Shark

I literally googled "C++ memory management" and here is what I found:

one, two, three, and many more relavent links.

Google "C++ avoiding memory leaks":

one, two, three, and many more relavent links.

As for books, go to a public library or a bookstore and search for C++ coding techniques, memory management, pointers, memory allocation, memory stack and heap, etc etc. There is also a sticky thread in this forumn about C++ books...lots of good references in there...just sift through them to see what you see...

Of course, best way to learn is to do... You can read all you want about memory management (or any programming technique in general), or find sites that tell you what to do and list rules to follow, but without practice, you won't understand how to apply your knowledge and problem solve.

Cheers!

The only problem with "practicing" is that I have no way to tell if there is a memory leak or not during run-time.

I have to know how to practice the correct way to prevent bad technique.

Thanks for the links though, I'll check them out.

-Alex

Alex Edwards 321 Posting Shark

Does anyone have an website they would recommend to me for learning Regex?

I have tried using the Sun's tutorial on Regex as well as the Pattern and Matcher classes that use Regex but I am not quite understanding it.

I'd like to use it to return the String values in "groups" whether a match has been made or not (because I don't care about the matches... I just want the String returned in the current parenthesized groups!).

Also further knowledge of Regex would be nice, but returning the value within a group alone would be a godsend.

Thanks --

--Alex

Alex Edwards 321 Posting Shark

Is there a website that has some kind of GUI or application that allows users to enter statements like--

delete

delete []

for... n elements... delete arr[n]

--etc so that they can learn good memory management?

I sifted around some free ebook sites and found one but the link to it was broken (the file couldn't be located on the server it existed on, poor popularity I suppose).

If anyone has a good book suggestion, or site where I can get some practice/advice on memory management I would really be grateful. I'd hate to be one of those problem-programmers that cause the dreaded memory leaks in team-projects.

Alex Edwards 321 Posting Shark

For question number 1 - is it possible to assign your array with a variable later?

Yes it is, because your array will receive "garbage" information until you give it values.

For example, you allocate memory for the array (either dynamically or from the stack - your call) and decide to display that indice of the array using cout. You'll realize that the number can range from 0 to the highest number that your data type can hold. For example..

int myIntArray[5];

cout << myIntArray[0] << endl;

Will display any particular number that an int can be (it's random, but only random once) because what I did was assign my array to have enough memory for 5 ints. I never gave it any values, so the values in the array (initially) will be what programmers call "garbage."

To answer your second question, replace system("pause") with this--

cin.get();

That will pause your program in most cases, however you should probably read the link "How do I flush the input stream" made by the expert meanie Narue. It will help you around some stream problems you will encounter as you learn c++.

Alex Edwards 321 Posting Shark

Hi All,

If i have choice to either use simple array(char a[]) or map.
Which one i shall use, whether array or map.
i need to know wich technique will give better performance.
As per my requirement i will insert the element in array/map, find the element based
on index.
I would appreciate your effort if you people could help me by telling as per performace
wise which is better if i have index of each element.

Thanks in Advance

Arrays are Random Access, which is fairly fast searching.

However, that's only if you know which indice the element is located at. Otherwise you'll have to do a linear search through like-elements to find what you're looking for.

Your best bet would be a map, and the type of map that you use would depend on how you're doing the search.

If you're looking for objects via comparison then I'd use a TreeMap (a map that holds information by key then searches for the element(s) you're looking for by comparing your key with other keys in a tree-like fashion).

You could also use a HashMap which is built for indexing, but I cannot explain that well enough to give a valid example.

Alex Edwards 321 Posting Shark

When your program is running and you need to allocate memory WHILE the program is running, dynamic memory allocation is the way to go.

Think of how restrictive programs would be if they always had to perform on limited memory.

There are more benefits to dynamic memory, but this is just one of them.

Alex Edwards 321 Posting Shark

Looks like you're going to make GOOD friends with--

--ASCI
--Subtraction

--because you can easily allow someone to enter a phrase and immediately convert the char value into uppercase.

After you convert the char value to uppercase, think about the value of the char in ASCI code then do subtraction. For example--

A = 65 in ASCI so to convert to your code from ASCI to number you'd need to do something like--

int someNumber = ((int)(someChar) - 64);

Now your character will have a number representation.

From there, your new best friends will be--

--int division
--modulus

--because the division will allow you to find out how much you need to carry to the next number to be evaluated, while modulus will determine the remainder value for an answer slot.

I'm assuming your modulus should be %27 because 0 counts as 0 and Z counts as 26. You never encounter the 27th indice because it doesn't exist! So whenever two "char-numbers" add and are over 27, you will need to do int division to determine the carry-value then modulus to determine the remainder-answer for that value.

This is pretty much iteration from the end of the char-array to the beginning. You'll also want to use "dummy-numbers" of 0's appended to the 2nd or first argument secretly so that you can continue to do char-addition without issue.

Alex Edwards 321 Posting Shark

Sorry I was not very clear, I actually did not understand the question fully myself.

Basically, the children of a node just become reversed:

so if node t has a kid named a and e, and a's right sibling is e, t would point to e and then a would be e's right sibling, and so on and so forth.

I have used your idea about reversing the list and still doesn't seem quite right, can you show me what I am doing wrong?

//creates the mirror image of the tree
		void mirror(){

			mirror(this->root);
		}

		//overloaded mirror image function.
		//TreeNode *node is a TreeNode node which is passed in to work with
		void mirror(TreeNode *node){

			node->leftChild = reverseList(node->leftChild);
			for(TreeNode *kid = node->leftChild; kid != NULL; kid = kid->rightSibling)
			
				mirror(kid);
		}

		//reverse list
		TreeNode* reverseList(TreeNode *node){
		
			TreeNode *temp1 = node;
			TreeNode *temp2 = NULL;
			TreeNode *temp3 = NULL;

			while (temp1){

				node = temp1; //set the head to last node		
				temp2= temp1->leftChild; // save the next ptr in temp2
				temp1->leftChild = temp3; // change next to privous
				temp3 = temp1;
				temp1 = temp2;
			}

			return node;
		}

Why not "swap" the addresses that t is pointing to?

#include <algorithm>

swap(a, e); //?
Alex Edwards 321 Posting Shark

Which Dev are you using?

I believe I'm using v4.9 and I always give myself a--

>Black Background
>Green text
>Red paranthesis/brackets
>Yellow Hexadecimal/Octal

etc...

I think you just need to go to your environment options to make the edits.

Edit: Go to your Editor options and go to Syntax - you can make the changes there.

Alex Edwards 321 Posting Shark

Hello!

Have you heard of the interface Comparable?

It allows you to compare like-objects with its implementation.

public static void sort(Comparable[] values, int start, int end)

If your class implemented Comparable you would be forced to include a method called compareTo(Object o)

The reason this is nice is because the compiler recognizes anything that implements the interface as a Comparable object, which means you can use an array of any objects you want for the argument of the method above so long as they implement Comparable.

You will need to override this method since it does nothing on its own. You can make some attributes for it, like so--

//Method to be included in your Property class

public int compareTo(Object arg) //comparing to another object (a different Property)
{
      if(arg instanceof Property) //if the object is-a property object
      {
             Property temp = (Property)arg; //Edit

              if(temp.propertyValue == propertyValue)
                  return 0;
              else if(temp.propertyValue < propertyValue)
                  return 1;
              else return -1;
      }
     return 99;
}

Now you can sort different property objects using the compareTo method. If you compare two Property objects and the value (from the method) returned is -1, you know that the class that used the compareTo method has a lesser property and should be placed before the class it was comparing to.

On the other hand, if the value is 1 then you know that the class that used the compareTo method has a greater value and should come after the class …

Ezzaral commented: Good post +9
Alex Edwards 321 Posting Shark

This is what you do when your bored ?!
I suggest you try learning the Win32 API to be able to make proper window applications, and then mabey move on to MFC when you get the hang of that. From there you should be able to make basic games / animation. Anything is more fun than this ^.^

Start with this tutorial
http://www.winprog.org/tutorial/

After 3 quarters of java I am tired of dealing with GUI's. There's just no way I can will myself to do it in C++ for any reason other than to learn the syntax involved with C-GUI's.

Alex Edwards 321 Posting Shark

I'm getting a really odd error in my program.

The lvl value retains its initial value if it's left alone, but when the program runs after you've assigned it a value it get's a ridiculous number... then the previous number after another assignment... and the process continues.

Here's the code.

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

using namespace std;

/**

Self-Learning session: Multi-threading in C++

Lesson learned: I might need to take a look into synchronization in order
to give proper values to objects that are constantly beind monitiored by other
Threads.

Not sure why lvl is always the previous number to whichever I assign it
from std::cin

*/

class Menu;
class Stats;
DWORD WINAPI runStats(VOID*);
DWORD WINAPI runMenu(VOID*);

class Stats{
      public:
             int hp, mp, lvl;
             bool running;
             
             Stats() : running(false) {hp = 0; mp = 0; lvl = 0;};
             
             void run(){
                if(!running){  
                  running = true;          
                            
                  while(true){
                       Sleep(5000);
                       cout << "Current HP is... " << hp <<"\n" << endl;
                       Sleep(2000);
                       cout << "Current MP is... " << mp <<"\n" << endl;
                       Sleep(2000);
                       cout << "Current LVL is... " << lvl <<"\n" << endl;
                       Sleep(2000);
                  }
                  running = false; //this should not occur since the above is an infinite loop.
                }
             }
};

class Menu{             
      public:
             
             Stats *myStats;
             bool running;
             
             Menu(Stats *objStats) : running(false){
                    myStats = objStats;    
             }
             
             void run(){
                  if(!running){
                      running = true;        
                      bool stopped = false;
                 
                          do{
                              char answer1[200] = {0};
                      
                              cout << "Do you want to alter the stats?" << endl;
                              cin >> answer1;
                      
                              if(answer1[0] …
Alex Edwards 321 Posting Shark

IF you know C# then you will have little difficulty converting it to java on your own. It will not take you much time to read a few things about java. If you know C# you don't need to learn anything new, just understand a few things about how java works.
If you know C# and you didn't just find someone else's code and you want to convert it to java for your assignment.

Yeah I agree...

Knowing C# takes some fair Java and C language know-how, along with the idea of delegates, partial classes, unsafe context, "member variables," etc...

Alex Edwards 321 Posting Shark

Hi guys,i am new to both c++ and this forum...I got a problem with a question i m supposed to do.I am supposed to create a queue system but i am stuck at a point where i can't add numbers to the queue system.This is the question...
You have been assigned to code the world longest queue that can store up to a maximum of 10 integers.

Create a queue system interface with the following functionalities:
- option to Add number to end of queue
- option to Remove number from end of queue
- option to Sort queue in ascending order
- option to Show queue content
- quit
Sample Output:

Queue System [Free: 10]
==================================
1. Add number to end of queue
2. Remove number from end of queue
3. Sort queue in ascending order
4. Show queue content
5. Quit
Choice: 1

Enter the number to add: 10

The problem is that i can't add number to the queue.Here is my code...

# include<iostream>
using namespace std;

void show(int a[],int size)
{
	for(int b=0;b<=size;b++)
	{
		cout<<"Item "<<b<<": "<<a[1]<<endl;
	}
}
void subno(void)
{
	int sub=0,b=0,c=0;
	cout<<"Status: Last number successfully removed."<<endl;
	
}
void addno(void)
{
	int arr[10];
	int b=0;
		cout<<"Enter number to add: ";
		[B]for(int i=0; ;i++)[/B]
		{
			cin>>arr[i];
		}
}
void main(void)
{
	int b=10,c=0,e=0;
	int a=0;
	do
	{

			cout<<"Queue system [Free:"<<b<<"]"<<endl;
			for(int f=1;f<36;f++)
			{
				cout<<"=";
			}
			cout<<endl;
			cout<<"1. Add number to the …
Alex Edwards 321 Posting Shark

Thanks for your reply.

I changed my code as follows:

T* pop();

template<typename T>
T* Stack<T>::pop(){

T *value = &elems.back();
elems.pop_back();

return value;
}

but when I do this in my main...

Stack<int> myStack;

myStack.push(2);
myStack.push(3);

cout << myStack.pop() << endl;
cout << myStack.pop();

what is displayed is still the address not the actual value...

any ideas?

Notice that your pop method returns a pointer. Remember that when you make a call such as..

int a = 5; *iPtr = &a;

cout << iPtr << endl;

You're return the address the pointer is pointing to and not the value. What you want to do is dereference your method so when pop is called the actual value is displayed and not the address--

cout << *myStack.pop() << endl;
	cout << *myStack.pop();
Alex Edwards 321 Posting Shark

You're asking to return a pointer when you're really returning the address of an object that has fallen out of scope--

T value = elems.back(); //T value is a temporary object
 
elems.pop_back();
 
return &value; //the object in value fell out of scope before return

I'm honestly surprised you didn't get a compiler warning. Normally that happens when you attempt to return the value of a temporary object.

Try--

T *value = &elems.back(); //T *value is now a pointer that points to the address of 
                                       //the object 
elems.pop_back();
 
return value; //value should still exist
Alex Edwards 321 Posting Shark

Try this--

Add all of your files (the .h ones included) to a project and be sure to mark each .h file with the preprocessor definition of pragma, like this--

#pragma once

so the file isn't included twice.

Notice that even though your header files are in the same folder/project that you will have to include them for each .cpp file in the project.

Kinda like this--

/**
Class 1
*/

#include "header1.h"
#include "header2.h"
/**
Class 2
*/

#include "header1.h"
#include "header2.h"
/**
header1.h
*/

#pragma once
/**
header2.h
*/

#pragma once

You'll notice that you wont need the .h files in your project, but instead in the "default" directory for whatever program you're using to build your projects.

What I'd suggest is to make a new project and add 2 new files to them, name them with the class names and copy and paste the data that you want in separate classes to those classes.

Afterwards make two more files but save them with the .h extension instead of the .cpp and copy and paste the information you want as header files in those files.

Once that's done, move them to the default directory (or leave them where they are) such that you can include both header files without having to directly place them in your project.

I hope that makes sense.

Alex Edwards 321 Posting Shark
Alex Edwards 321 Posting Shark

I hear this argument a LOT and hear that templates/generics are far more superior in code production than virtually-driven classes.

I still don't understand this. I've heard the virtual functions cause problems for performance and that the solution is always to use Templates/Generics.

Do they mean that it is better to have a Generic class that has a Template parameter of the base classes and runs individual methods of the same name vs Inherited members with virtual functions?

I still can't really picture this scenario, yet I know it's important to know the difference since many programmers seem to stress the importance of using Templates in place of Inheritance.

Could the other problem be that it's confusing for programmers to know (by heart) the extensions of classes and their separate functionalities? I was browsing Microsoft's .NET section in their MSDN site and noticed that they implemented new syntax just to code around Inheritance issues.

Alex Edwards 321 Posting Shark

It compiled without error for me. What error message(s) did you get with your compiler. I used VC++ 2008 Express.

I don't think he meant that it had errors but that he couldn't build the files in separate .cpp files outside of a project.

My question to the original poster, did you try adding your .cpp files to a different project, or using --

#include "filename.h"

--for header files in your "default" directory?

I don't think you can run the files without a project, or at least I never can. I use Dev-cpp 4.9 and it's always been like that for me.

Alex Edwards 321 Posting Shark

I knew it was the condition in the while loop! I kept thinking "what if both leaf nodes aren't null" but couldn't wrap my head around the problem.

You rock!

Alex Edwards 321 Posting Shark

Thank you for the revision, but the main problem is that it seems the tree loses track of some of the values I insert.

Edit: Nevermind, I miscounted...

I better get some sleep.

Edit 2: Wait actually yeah 7 is not being input...

Alex Edwards 321 Posting Shark

Wow I never thought of using a pointer-struct for each and every piece of data and holding an initializer. I'm not sure why but I couldn't think of something like that >_< .

After looking at nothing but code for the last few days my imagination slipped slightly so I couldn't think of anything like that...

and R.E. you cease to amaze me. Thanks a million!

Alex Edwards 321 Posting Shark

I don't understand... I thought that it would be functional based on the logic, and I was fairly careful with my syntax but it's still not working.

Sometimes values will compare to as being "equal" even though they're not. I'm using troolean compareTo method (an int, returns -1, 0 or 1) and if two values are equal the value isn't set in the tree but it's testing two values incorrectly at some times...

Furthermore the pointer temp in the insert method doesn't seem to be reassigning itself properly.

Can someone please help me understand my error?

#include <cstdlib>
#include <iostream>

using namespace std;

/*

*/

struct Base
{
       
};

template<typename T>
class Tree
{
      private:
             struct Node
             {
                 friend class Tree;
                 
                 Node *left;
                 Node *right;
                 T value;
                 
                 Node(){left = 0; right = 0;};
                 T &getValue(){
                     return value;
                 };
                 void setValue(T &arg){value = arg;};
                 Node &getLeft(){return *left;};
                 Node &getRight(){return *right;};
                 bool setLeft(Node &l){
                      if(&l != 0){  
                         left = &l;
                         return true;
                      }
                      else return false;
                 };
                 bool setRight(Node &r){
                      if(&r != 0){
                         right = &r;
                         return true;
                      }
                      else return false;
                 };
                 int compareTo(Node &other){
                     if(other.getValue() == getValue())
                         return 0;
                     else if(other.getValue() < getValue())
                         return 1;
                     else return -1;
                 }
             };
             Node *root;
             void displayInOrder(Node &arg)
             {
                  if(&arg == 0)
                      return;
                  
                  displayInOrder(arg.getLeft());
                  std::cout << arg.getValue() << std::endl;
                  displayInOrder(arg.getRight());
                  
             }
             void displayPreOrder(Node &arg)
             {
                  if(&arg == 0)
                      return;
                      
                  std::cout << arg.getValue() << std::endl;
                  displayInOrder(arg.getLeft());
                  displayInOrder(arg.getRight());
                  
             }
             void displayPostOrder(Node &arg)
             {
                  if(&arg == 0)
                      return;
                  
                  displayInOrder(arg.getLeft());
                  displayInOrder(arg.getRight());
                  std::cout << …
Alex Edwards 321 Posting Shark

Maybe you could use a bitset for tracking the assignments.
Two things I noticed:
- use of realloc() would result in fewer malloc/free calls
- you should test malloc's return value against NULL

I'm not well learned enough with realloc but I'll give it a shot.

Realloc's job is simply to add additional memory to an existing pointer, correct?

Edit: And I completely forgot that malloc could return 0 in some cases. Good call.

Alex Edwards 321 Posting Shark

Thanks a million, both of you =)

Alex Edwards 321 Posting Shark

Odd, I'm not getting that error at all...

Did you include the preprocessor directives for cstdlib and iostream? Also are you using namespace std?

It ran fine for me, no weird operator errors.

Alex Edwards 321 Posting Shark

I tried compiling the code but I think some of it is written in french? O_o

Alex Edwards 321 Posting Shark

I was working with my own "Vector"-like class and thought about something.

If I use the [] operator and return a reference, is there any way to mark that indice when a value is assigned to it?

For example.. if I want to make a trim function that removes the "garbage" information when I allow the user to specify a size for the Array Class and call trim.

Here's the code in case you need to see it.

#pragma once

/*

MyLibrary.h

Meant to be used with stack-objects only. Namely primitive types (hence the name).
*/

template<typename P>
class PrimArray{
      private:
              P *value;
              int currentSize;
              
      public:
             PrimArray(){
                  int temp = 1;           
                  value = (P*)malloc(temp * sizeof(P)); 
                  currentSize = temp;      
             };
             
             P *copyContents(){//returns a deep copy of this array-class
                  P *copy = (P*)malloc(currentSize * sizeof(P));
                  
                  for(int i = 0; i < currentSize; i++)
                          copy[i] = (*this)[i];
                  
                  return copy;            
             }
             
             ~PrimArray(){free((void*)value);};
             
             int length(){return currentSize;};
             
             bool storeValue(P arg, int location){
                 if(location >= 0 && location < currentSize){         
                   (*this)[location] = arg;
                    return true;
                 }
                 else if(location == currentSize){
                     P *temp = (P*)malloc(currentSize * sizeof(P));
                     
                     for(int i = 0; i < currentSize; i++)
                          temp[i] = (*this)[i];
                      
                     currentSize++;
                     free((void*)value);
                     value = (P*)malloc(currentSize * sizeof(P));
                     
                     for(int i = 0; i < currentSize; i++)
                     {
                        if(i != (currentSize - 1))     
                           (*this)[i] = temp[i];
                        else (*this)[i] = arg;
                     }
                     free((void*)temp);
                     return true;
                 }
                 else{
                     std::cout << "Could not store value at indice: "<< location;
                     std::cout << ". " << "\nCurrent size is: "<< currentSize << …
Alex Edwards 321 Posting Shark

Gotta love the SWAP macro too...

#define SWAP(a, b) __typeof__(a) temp; temp = a; a = b; b = temp
Alex Edwards 321 Posting Shark

I'm not sure how to approach this problem.. mostly with the while statement..
Download the original attachment

The Problem:
Write a program on timber regrowth of a harvested forest. The user is to enter the total number of acres in the harvested area, the number of acres which were left uncut, and the reforestation rate. The program will then determine how many years are required for the number of cut acres to be completely restored. Your program should display the initial conditions, and display the progress made as each year passes in a table.

It is assumed that reforestation takes place at a known rate per year, depending on soil and climate conditions. A reforestation equation states this growth as a function of the amount of timber standing and the reforestation rate. So for year x, the total reforested acres of timber = (starting total forested acres for year x -1) times (reforestation rate), so if the starting total forested acres for year x -1 is 1000, and the reforestation rate is .04, then the total reforested acres of timber for year x = 1000 + 1000 * .04 or 1040 acres, for year x + 1, the total would be 1040 + 1040 * .04 or 1081.6 acres.


Example:

Enter total acres: 12000
Enter acres uncut: 3000
Enter reforestation rate: .04

Year Forested Acres
0 3000.00
1 3120.00
2 3244.80
3 3374.59
... ...
36 12311.80


Alex Edwards 321 Posting Shark
// what will 'cmp' be ...
const int cmp = s_manip.compare("abc","abcd");

// what will 'cmp' be ... const int cmp = s_manip.compare("abc","abcd");

My bad ... sorry about that one ...

Honestly I'm more thankful than anything.

If I simply stuck to the book I've been reading currently and not coming to these forums my coding would've been incredibly bad, or at least unlearned.

You haven't given me any bad advice so far, so I don't take something "wrong" as an offense whatsoever.

Alex Edwards 321 Posting Shark

This is an example of recursion.

When you send the number 5 into the method simpleMeth() it will call the method simpleMeth(4) before reaching the print statement. Then simpleMeth 4 will call simpleMeth(3) before it reeaches the print statement.

This process will continue until simpleMeth reaches 0, where it will return the current status of i - in this case 0 is first printed... now that the simpleMeth(0) method is finished executing, the method before it (simpleMeth(1)) will finish executing and print 1...

This process keeps going until finally the initial method is done executing.

Keep in mind that a method has to perform functionality before execution ends. If you were to change the code such that println came before the decremented method call you would see the reverse process since the print statement occurs before the recursive method is called.

Alex Edwards 321 Posting Shark
// what will 'cmp' be ...
const int cmp = s_manip.compare("abc","abcd");

I've tested that... it turned out to be false. I don't understand the point you were trying to make here.

A diagnostics suggestion, add the following destructor

~Game_Object()
{
    std::cout << "~Game_Object(): " << objName << std::endl;
}

It will tell you that the memory management is not right.

At first I was trying to make copies of the objects and reassign them in the addObject command, but then I decided to simply delete already allocated memory then allocate more memory for new objects and assign the old objects (along with the new one) back to the pointer.

You already have a Game_Object * in obj, you don't have to allocate and assign a new Game_Object ..

obj[i] = new Game_Object[1]; // you don't need this line
obj[i] = tempPtr[i];

Made the change, thank you. As you can see I am still not quite understanding pointer to pointers.

Then strlen() returns the length of a string excluding the terminating NULL character but strcpy copies the string and appends the terminating NULL character <-> you have many one-byte-off memory allocations/assignments/overwrites there.

I did try using strcmp but apparently there were problems comparing a string literal with a char array that had extensive null terminators.

Then an example of a practice you effectively use

struct test
{
    int member_var;
    
    test() : member_var(0){}
    ~test(){}

    void f()
    {
        cout << member_var << endl;
    }

    static test & getObj()
    {
        test …
Alex Edwards 321 Posting Shark

Hello everybody,, this is a simple java method that calls itself,,

class ex{
     public static void main(String [] args){
              simpleMeth(5);
 }
     static void simpleMeth(int i){
        if(i != 0){
              rec(--i);
              System.out.println(i);
        }
    }
}

If you follow the the codes you will find after sending number (5) to the method then will be tested by the if statement(line n.6) then comes again to the method(line n.7) so (i) will be 4, and will continues until (i) equals 0,,but why after ending the if statement and comes to the method end brace,returns again to the printing statement and printns (0) then goes to line n.10 and adds one to (i) and returns again to line n.8 and so until (i)equals 4 ..
the result is:
0
1
2
3
4

Hope understand what i mean :)
Thnx..

Where is rec defined?

if(i != 0){
              rec(--i);

You didn't post all of the code =/

Alex Edwards 321 Posting Shark

Instead of using the double generator from the Math class you can try using the Random class from java.util.Random extension. I modified your code to implement it--

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.Math.*;
import java.util.Random;

/*
*Author: John Pycroft
*Date CR: 15/6/2008
*Date LM: 15/6/2008
*Name of project: Minesweeper
*/

public class Minesweeper extends Applet implements ActionListener, KeyListener
{
	Random rgen = new Random();
    Button mineField[][];
    int numberMine[][];
    int xSize, ySize, mines;
    TextField X, Y, Mines;
    Button Expert, Intermediate, Easy, Submit,Restart;
    Label x, y, mInes;
    boolean secondTime;
    public void init()
    {
        if(secondTime)
        {
            remove(x);
            remove(X);
            remove(y);
            remove(Y);
            remove(mInes);
            remove(Mines);
            remove(Submit);
            remove(Easy);
            remove(Intermediate);
            remove(Expert);
            Button mineField[][]=new Button[xSize][ySize];
            int numberMine[][]=new int[xSize][ySize];
            for(int row=0; row<mineField.length; row++)
            {
                for(int collum=0; collum<mineField[0].length; collum++)
                {
                    mineField[row][collum]=new Button("");
                    mineField[row][collum].addActionListener(this);
                    add(mineField[row][collum]);
                }
            }
            for(int i=0; i<mines; i++)
            {
                numberMine[rgen.nextInt(xSize)][rgen.nextInt(ySize)]=42;
            }
        }
        else
        {
            X=new TextField(30);
            Y=new TextField(30);
            x=new Label("Custom X");
            y=new Label("Custom Y");
            mInes=new Label("Custom Mines");
            Mines=new TextField(30);
            Easy=new Button("Easy");
            Intermediate=new Button("Intermediate");
            Expert=new Button("Expert");
            Submit=new Button("Custom Field");
            Easy.addActionListener(this);
            Intermediate.addActionListener(this);
            Expert.addActionListener(this);
            Submit.addActionListener(this);
            add(x);
            add(X);
            add(y);
            add(Y);
            add(mInes);
            add(Mines);
            add(Submit);
            add(Easy);
            add(Intermediate);
            add(Expert);
        }
    }
    public void actionPerformed(ActionEvent e)
    {
        if(secondTime)
        {
        }
        else
        {
            if(e.getSource()==Submit)
            {
                xSize=Integer.parseInt(X.getText());
                ySize=Integer.parseInt(Y.getText());
                mines=Integer.parseInt(Mines.getText());
                secondTime=true;
                init();
            }
            else if(e.getSource()==Expert)
            {
                xSize=30;
                ySize=16;
                mines=99;
                secondTime=true;
                init();
            }
            else if(e.getSource()==Intermediate)
            {
                ySize=xSize=16;
                mines=40;
                secondTime=true;
                init();
            }
            else if(e.getSource()==Easy)
            {
                xSize=ySize=8;
                mines=10;
                secondTime=true;
                init();
            }
        }
    }
    public void keyPressed(KeyEvent e)
    {
    }
    public void keyReleased(KeyEvent e)
    {
    }
    public void keyTyped(KeyEvent e)
    {
    }
}

Edit: Unlike C++, you can initialize your variables …

Alex Edwards 321 Posting Shark

The code you oposted has a huge memory leak. Line 24 allocates some memory then line 25 tosses the pointer away and uses it for something else. One of those two lines needs to be deleted. My preference is to keep line 24 and delete line 25 so that the class has complete control over all its data.

Since MyClass does not own the memory for Other1 and Other2 (see lines 25 and 26) the MyClass destructor will most probably cause a core dump or some other nasy abnormal segmentation fault. You can not delete[] something you did not allocate with the new operator.

line 48: you compiler will give you an error on that line because you do not call destructors explicitly.

Thanks everyone for your responses. I didn't realize my projects were causing such incredibly memory leaks. I'll look out for them.

And AD, my experience with allocating memory for double pointer has been the following--

--Whenever I declare a double pointer (for a class for example) and don't allocate memory for the pointers, my program shuts down on me because I'm supposedly trying to assign data to memory that I shouldn't have access to...

Which makes no sense because I thought that you could assign the initial value of the pointer to a valid reference regardless of whether you've allocated memory for it or not... This is the most confusing thing for me from switching from java to C++ because it feels like there …

Alex Edwards 321 Posting Shark

Whenever I try to declare a "Regular Expression" while including symbols like "+", "-", "*", the match is done based on how those operators work.

Now, when I try to use the regex API via combining those operators with backslash or \Q and \E I get the error message--

"...Illegal escape character".

I'm using TextPad at the moment, however the error is thrown by the compiler which makes me wonder if I need to upgrade or if there's a specific file to download to use regex API legally.

Alex Edwards 321 Posting Shark

Right now I feel fairly unlearned with dynamically allocating memory... even after doing so several times and doing projects that require one to dynamically allocate memory for classes and primitive types.

Basically, how does one research allocation for different scenarios such as...

#include <cstdlib>
#include <iostream>

using namespace std;

class Other
{
};

class MyClass
{
     public:
           int amount;
           Other **other1, *other2;           

           MyClass(Other *ot, int size)
           {
                   amount = size;
                   other2 = new Other[size];
                   other1 = new Other*[size];
                   
                   for(int i = 0; i < size; i++)
                   {
                             other1[i] = new Other[1];
                             other1[i] = &ot[i];
                             other2[i] = ot[i];
                   }
           }
           ~MyClass()
            {
                    for(int i = 0; i < amount; i++)
                    {
                             delete other1[i];
                    }

                    delete other1;
                    delete other2;
            }
};

int main(int argc, char *argv[])
{
    
    Other o[5];
    
    MyClass mc (o, 5);
    
    mc.~MyClass();
    
    cin.get();
    return 0;
}

Is the above correct?

I've been looking through various sites for examples of how to properly deallocate memory or assign objects to pointers with allocated memory and the usual examples only include 1 pointer.

Edit: Also, what should I do when I don't have a primary void constructor when allocating memory for that object for a double pointer? What then?

Alex Edwards 321 Posting Shark

i like the isSolvable method,
i also like the idea of pre-defined stuff, i could save a lot of processing time, but because it is impossible to predict what a user will think of, i think it would be interesting to have a log-type of file:
i think it would be cool to get an equation, and search the log for it and if it is there it will substitute in the simplified form in the file,
and if not simplifies it and adds it to the log.
thinking of it now, to populate the initial log, i could release the program (whenever i final figure it out) to a few or more people who will later give there logs back after a while, and combine them to get an original.


what i actually have is here:[ATTACH]6339[/ATTACH] this actually contains the bluej project folder, the actual parsing is taken care of the stuff in the parser folder, creating a tokenizer with a string parameter will do what it needs to do, it will print out the parts

I've been looking into a few sites to see if group-parsing can be done in an easier fashion (i.e. parsing a group from the "deepest" paranthesized group then simplifying that expression and appending the simplification back to it's proper location in the String).

I found a few that are useful in case your idea doesn't work out. I've been studying and tinkering around with the "Pattern" …

sciwizeh commented: gave valid info +1
Alex Edwards 321 Posting Shark

I wrote down the process of how the program must run efficiently. Tell me if anything is wrong with this--

User
*user needs to provide equation
*user needs to specify the different variables in the equation

Equation
->Check for syntax errors
->Perform Calculation in order of operations PEMDAS
->Combine like-terms
->Simplify (not solve) the equation

Here is what I have so far. Although it's not much it may be of some help.

Alex Edwards 321 Posting Shark

i already have it breaking into smaller pieces, it's getting the pieces to do the right thing that i'm having trouble with.
i have a class for these pieces (see above post), and i am not sure how i should go about having it find a value.
say for example i have an array list of instances and the second (.get(1)) contains the substring "+", it would have a type of 3 and a type_of_type of 1, both constants at the top.
it also has an a reference to the instance before it in the array list and the instance after it (.get(0), and .get(2)).
so in the value method of it there would be an if statement for the type, and then the type of type, if the type is 3 (binary operator) it would have to preform the operation with the two surrounding it.
but if one of those happens to be a variable (x) then it cannot preform the operation unless a value is already given to the variable (x) and if that is the case (no value) than it should return the string ("x +" + instance after) and if that gets returned than the rest of the whole string would have to work with that instead of a number.

i want the program to be able to tell me that 6+6*6 is 42 (PEMDAS) but i also want it to tell me that (x+1)*(x+1) is x^2+2x+1

am i being clear …

Alex Edwards 321 Posting Shark

Nevermind about the comparison, I created a class that does char pointer to char pointer comparisons.

My biggest problem now is the process of running the engine part's run overridden run method.

I have the revised files listed with the addition of the class I created to do the comparison.

Edit: Did some more revisions... found the error.

I was attempting to "free" memory from the previously allocated indice in the addObject portion of the code but I simply deleted the pointer gluing the other pointers together causing them to float freely, then allocated them to a temporary pointer then reallocated them to the regular double pointer... Hopefully I did this process correctly.

At the moment no information is lost and the virtual run method is overridden by the user's Engine Part run method which is exactly what I wanted. If there's still a problem with this please let me know.

Game_Object **tempPtr = new Game_Object*[amount];
                              
                           for(int i = 0; i < amount; i++){
                              tempPtr[i] = new Game_Object[1];     
                              tempPtr[i] = obj[i];
                           }
                           delete[] obj; //deletes the pointer pointing to the pointers, causing the pointers
                                         //to "float" freely in memory, but tempPtr holds a ref to them
                           
                           obj = new Game_Object*[amount];
                          
                           for(int i = 0; i < amount; i++){
                              obj[i] = new Game_Object[1];
                              obj[i] = tempPtr[i];
                              
                           } 
                          delete tempPtr;
Alex Edwards 321 Posting Shark

Those are not compiler warnings but instead run-time checks wrt heap usage. The compiler will not catch the errors that occur in the program, but the run-time checks will alert you on the spot. Try e.g. a VC ++ Express 2008.

It appears that you are not yet fully understanding about memory allocation/deallocation, so
if you use the malloc/free, every pointer you 'free' must have been malloc'ed, no exceptions.
if you use the new/delete, every pointer you 'delete' must have been new'ed, no exceptions.

I'm also trying to say that if you have a non-dynamic 'object', you must not issue free nor delete on a pointer to such object. This in mind, go through the code and see what happens with e.g. [B]bound[/B] ("Bound"), [B]adephi[/B] ("Adephi"); .

I think I understand a bit more now. I've revised the code again and this time I also dynamically allocated memory for char pointers I declared in class-scope.

Here are the revisions again, and this time it seems as if the program is working... but if there are still errors please point them out.

Edit: Oh actually there is one issue - I'm having trouble comparing a null-initialized char-array to a char pointer. What would you suggest?

Alex Edwards 321 Posting Shark

Hmm, wouldn't it be better to drop usage of malloc()/free() since you are working with objects instead of raw native types i.e. consistently use new/delete. And maybe consider e.g. STL list for storing objects/object pointers, to save yourself the hassle of memory management.

Anyway, note that you must not issue free() on anything that has not been malloc'ed. That is just what is now happening in addObject(), that crashes the program at very early stages (before main() is called).

Ah I see what's happening.

Because I didn't use new on my objects, their constructors never ran therefore the data was never initialized in the first place!

Wow I learned an incredible lesson here.

The reason why I used malloc instead of new was because I was looking for an alternative around allocating memory for temporary/abstract objects since they require an extension and override within the extensions.

Apparently I was trying to cheat the system and I get bit in the ass for doing so =/

I'll make the changes again. Thank you very much.

Honestly, my compiler is not giving me these warnings! What compiler should I update to in order to get these messages?