dusktreader 137 Posting Whiz in Training

There is actually a very simple solution to this problem. First, you are trying to do two things here:

1.  Split an input number into separate digits.
2.  Add the digits together.

First of all, I would not recommend putting your input into an int type. If you do this, you have to split each digit using modular arithmetic. While this is mathematically elegant and very pleasing aesthetically, it is not the optimal solution here. Instead, one could store the input as a string. In this case, each character can then be interpreted as a digit in and of itself and processed accordingly. Then, in one pass, one could output each digit and accumulate a running sum. The method is summarized here in pseudocode:

set integer sum = 0
get input -> store in string s
for each character c in s:
    output c
    sum = sum + integer( c )
output sum

The tricky part here is converting each character to an integer. Fortunately, this is very simple in c++: int i = c - '0' This works because numbers in the ascii table are sorted in ascending order. Furthermore, chars are actually integers, so we can perform arithmetic on them. So, any numerical character minus the zero character results in the integer that the character represents: 7 == '7' - '0' Using this method, the algorithm you are trying to build can be defined in a concise main function taking only 13 lines of code ( …

dusktreader 137 Posting Whiz in Training

I'm making a red black tree (RedBlack class) whose nodes will contain customers (customer class) rather than the generic int data. Unfortunately, I can't seem to get VS 2008 Express recognize that data is of type customer. I get all sorts of redefinition errors, and I've tried pragma once and include guards to no avail.

class RedBlack
{
private:
	struct node {
		bool red; //True if red, False if black
		[B]int data; //customer data[/B]
		struct node *next[2]; //pointer to an array where index 0 is left and index 1 is right
	};
	node *root;
	[B]customer data;[/B]
	struct tree{
	struct node *root;//pointer to the root
	};
public:
	RedBlack();
	bool isRed(struct node *root);
	~RedBlack(void);

//#endif

Per this code, each node's data item is an int, but the tree itself has a single customer data item. You should probably make the struct contain a customer data item.

dusktreader 137 Posting Whiz in Training

Sorry dustreader, but if you are going to be using the STL, do this:

// Assign players in any order (not random)
shuffle(players,players+10);

O RLY?

You didn't notice that I mentioned this exact approach in my post. I decided to show random selection to give the OP an idea of how one can randomly choose and remove a single element from a container.

Of course, I'm sure that in your haste to edify me you momentarily forgot the proper syntax: random_shuffle( players.begin(), players.end() );

The code given is horrific. It has three vectors etc...

As opposed to sending a learner down the path of inflexible non-extensible code? There are 3 vectors because it is assumed (as described by the OP) that there are different roles for different item types. Perhaps it was naive of me to make the logical deduction that since each separate item type performs a separate function on a specific item group, it would be nice to have them in separate containers. Of course, a polymorphic class hierarchy would be the preferred solution for this sort of algorithm. However, the OP probably doesn't want to tangle with classes and inheritance yet.

However Calyso8 is starting, so it is important for him/her to understand the algorithm and what the c++ is doing:

Right, and since the OP is learning, introducing the STL is probably a good idea so that when the OP starts using larger collections, the OP doesn't continually use statically allocated arrays …

dusktreader 137 Posting Whiz in Training

Hi, I am fairly new to C++ but love to learn, so I wanted to create a simple program base on the group-party game mafia A.K.A "werewolf."

Just so whoever is not familiar gets the background. I will use just an example of 10 players. In a ten player game, there consists of 4 roles and this is how many there will be in the game:

3 Mafia
1 Cop
1 Doctor
5 Innocent

I figured I would assign those roles "randomly" to each player using those limits. So

0= mafia, 1= cop, 2= doctor, and 3 = innocent

I got somewhat of the code running ok only when generating a 3 player game. I only know how to use a bunch of "IF's" statement, if anyone knows how to make things easier, please feel free to teach me.

I would suggest that you use a random selection from a collection to build your groups. You could do something like this

int n; // Some number of items
int aCt = (int)( PCT_A * n );
int bCt = (int)( PCT_B * n );;
vector<Item>itemPool( n );
vector<Item>poolA;
vector<Item>poolB;
vector<Item>poolC;
srand(time(0));
int pick;
for( int i=0; i<aCtt; i++ )
{
    pick = rand % itemPool.size();  // Notice that the pool size is shrinking
    poolA.push_back( itemPool[pick] );
    swap( itemPool[pick], itemPool.back() );
    itemPool.pop_back();
}
// Create similar loop for poolB
poolC.insert( poolC.begin(), itemPoolbegin(), itemPool.end() );  // Put the remainder into poolC

It is helpful to utilize the

dusktreader 137 Posting Whiz in Training

I found it pretty easy. Check this link.

Thanks a lot, Fbody....There goes my productivity for this morning...

dusktreader 137 Posting Whiz in Training

i am trying to make a program where a user inputs two numbers. the first number needs to be less then the second. then the program needs to add all the numbers together that fall between those two numbers including the two numbers. for example number1 = 1, number 2= 3.
the program need to output the sum of 1+2+3.

so far all i have is and i dont know what else to do.

#include <iostream>
#include <conio.h>
using namespace std;
int main()
 {
	 int n1;
	 int n2;
	 int total;

	 cout<<"enter n1: ";cin>>n1;
	 cout<<"\nenter n2: ";cin>>n2;

	 while (n1<=n2)
	 {
		 n1=n1+(n1+n2);
	 }
	 
	 cout<<"\ntotal is: "<<n1;
	getch();
}

You need to use your third totalvalue to accumulate the sum. That is, add n1 to it on every step. Also, on every step of the loop increment n1 by 1 ( n1++ ). Finally, you need to be careful about how the loop terminates. Does the sum include n2? If not, your termination expression needs to be n1<n2 You're close, but still have a some work to do.

dusktreader 137 Posting Whiz in Training
case 'a':
			{
				//Create an object and return a pointer to that object
				//(I will be making many of these objects)
				[B]Base::ReturnPtrToANewBaseClassObject();[/B]

				//push the returned pointer onto the std::list
				BaseList.push_back( ptr );

				cout << "Object now pushed onto list" << endl;
				break;
			}

This is the way that you would call a static class function. Static functions allow you to call a function belonging to the class without having an instance of the class created. However, you must use the static keyword when defining the function in the header file. See this for more information.


Also, the ReturnPtr....() function returns a pointer, but you are not storing this value. You could either do this on two lines like:

Base* ptr = Base::ReturnPtrToANewBaseClassObject();
BaseList.push_back( ptr );

or on one like

BaseList.push_back( Base::ReturnPtrToANewBaseClassObject() );

All that being said, I think you are going down a bad road here. What you are essentially doing is creating an instance of an object with some specific value. This is exactly the function of a constructor. I would recommend that you use a constructor to accomplish this. However, I wouldn't use cin inside of the constructor. Instead, in the main program ( or wherever it is needed ) i would request the input, and then pass the input string off to a constructor to create a new Base object. Something like:

Base::Base( string someStr )
{
    _mystring = someStr;
}

int main()
{
   string inStr;
   cout << …
Carrots commented: Thanks for helping me out. thumbsup'jpg +1
dusktreader 137 Posting Whiz in Training

can I call a function B outside a class (say, a global function) from a member function Aof that class? if so, how do I specify the scope? Using :: B ?

thanks.

If B() is truly global, you call it like this ( brace yourself ) B() . And the best part is, you can call it like this from anywhere, including inside of a class function, because it is global.

dusktreader 137 Posting Whiz in Training

Since your 2D data is being stored in 1D arrays, all you need to do here is play indexing games. Suppose you had a matrix of MxN stored in a 1D array M*N in length. If the matrix is stored in column major order, and you need to convert it to row major order, you will have to do some copying. So, try this approach:

0.  Given an MxN ( M=width, N=height ) Matrix ( mat0 ) stored in column major order in a 1D array ( arr0 ) of length M*N
1.  Create another 1D ( arr1) array of the same size (M*N) that will contain the matrix when it is converted to row major order
2.  Iterate over arr0 using an index value ( idx0 ) beginning at index 0 to M*N ( the length of the array )
3.      Compute an index ( idx1 ) into the row major matrix the column major array index ( idx0 )
4.      Store arr0[idx0] into arr1[idx1]

To do step 3, you should take advantage of integer division and modulo properties. Namely

For row major matrices:

row = index / width;
col = index % width;

For column-major indices

row = index % height;
col = index / height;

Hope this helps!

dusktreader 137 Posting Whiz in Training

This sounds like a computer vision problem. This is an ambitious project, though not at all impossible. Like @tetron suggested, you should do a lot of reading first. Then you might want to check out OpenCV. OpenCV is a powerhouse foss computer vision library that is really great at doing everything from linear algebra, to image processing, to object classification. It includes many machine learning algorithms including decision trees, support vector machines, and neural networks.

dusktreader 137 Posting Whiz in Training

Please post the nature of your errors ( syntax, logical, segfault, etc ) as well as your compiler/application output.

dusktreader 137 Posting Whiz in Training

I'm making a binary expression tree, and to do so I'm reading in values and putting them into a tree node and a pointer to that tree node into a stack. How do I use the STL stack implementation with pointers to my TreeNode class?

relevant code:

stack<TreeNode> s; 

TreeNode * a = new TreeNode(val);
s.push(a);

TreeNode is a class I created.

You have to declare the stack with a template prameter of TreeNode*:

stack<TreeNode*> s;
TreeNode* a = new TreeNode( val );
s.push(a);

That should do the trick. Remember that the template prameter is always atype and an object is a different type than a pointer to that type of object.

dusktreader 137 Posting Whiz in Training

As a post note, the sort function will also work on user defined classes without a third parameter (comparison function) if the class has overloaded the < operator.

dusktreader 137 Posting Whiz in Training

Yes, after adding "flush", the output came out! Thanks! Been doing C++ for a long while but never noticed this problem. Why didn't it happen anywhere else, since I have written many programs which ended with "endl" and never had problem?

P.S. logicmonster: cin.get() can't be the problem, since change about that makes no difference. Without that, any output would flash and go away.

Ok, so the problem was that endl wasn't flushing the output buffer like it is supposed to. See, when you use cout, the output doesn't get sent to the output device immediately. Instead, it is held in a buffer until the operating system decides to send the output to the device. So, the output in your code was just waiting in the output buffer while the OS asked for input. The endl keyword is supposed to trigger a flush, but obviously didn't. A flush simply tells the OS to send all output waiting in the output buffer to the output device now. In c++ you can use the flush keyword to do this explicitly. Also, having a newline character ('\n') in a string sent to output is supposed to flush output as is the endl keyword.

It really is strange that your compiler didn't include a flush with endl, and I would seriously consider using a different one

dusktreader 137 Posting Whiz in Training

You can not determine the time of execution

You can determine the time of execution. While the time is dependant on system load and hardware, you can still get an idea of performance using timing methods. After all, that's what they do in the industry to compare software. The easiest method is probably to use the clock() function that is part of <ctime> ( or <time.h> ) int the standard template library. Note that you will need to use the CLOCKS_PER_SEC macro to convert the value from clock ticks to seconds ( expressed as a double if you do it right ).

The Insertion Sort is the best algorithm for sorting...

Dead wrong. Insertion sort is great with very small lists, but not so good with large lists. It's best case performance is O(n) which seems nice, but this will hardly ever happen with real data. Instead, you are much more likely to get the average and worst case performance of O(n^2). Usually, for simple implementations, quicksort or mergesort are two of the better performers.

dusktreader 137 Posting Whiz in Training

Here is the simplest program:

#include <iostream>
using namespace std;

int main()
{
    cout << "hello" << endl;
    cin.get();
   return 0;
}

When I ran it (using Dev C++), there is no output, just a blank screen. The problem seems to be from the "endl". If I delete it, or to replace it with
"hello\n"
then it displays the output "hello" as expected.
It would also work well if I just add another cout statement after the original cout, while keeping the "endl".
Why is the problem with "endl"?
Thanks in advance!

That is strange behavior. I'm curious if the output isn't getting flushed like ti should. Try this: cout << "hello" << endl << flush; The endl keyword is supposed to flush the output buffer, but perhaps your compiler doesn't add that functionality.

dusktreader 137 Posting Whiz in Training

Did you even read that link you posted? It doesn't have to be a struct, but you can use one that has a bool function in it. All you really need is a function that returns true when the items being compared are in proper order.

Oops. You are correct. I should have read the link more carefully.

Fbody commented: a point for admitting your mistake +1
dusktreader 137 Posting Whiz in Training

I would appreciate if someone could help me sort out how to do this with accumulate (and also then how best to raise all of the vector elements to the exponent value before submitting them to the function). If not with accumulate, I'd appreciate any advice on how to do this efficiently.

The trick is implementing the function you pass to accumulate. Here is a demonstration that uses a vector of int pointers:

#include <iostream>
#include <vector>
#include <numeric>

using namespace std;

template <class T>
T adder( T init, T* iter ){ return init + *iter; }

int main(){
    int n = 1000;
    vector<int*> values( n, NULL );
    for( int i=0; i<n; i++ )
        values[i] = new int(i);
    int init = 0;
    int result = accumulate( values.begin(), values.end(), init, adder<int> );
    cout << result << endl;
    return 0;
}

The trick is that the adder function gets the init value as its first argument. The second argument is the iterator for the element to be accumulated next. In our case, this is a pointer, so we need to dereference it. I hope this helps and is the sort of solution you were looking for. Note that you could make adder a static function belonging to a class of type T.

StuXYZ commented: Clear example +3
dusktreader 137 Posting Whiz in Training

Hi all,

I've spent the last week trying to sort this out, and the more I delve into it, the more confused I'm getting. I've done some background research (searched on google and here for sort function issues) and really I can't make head or tail of what's going on.

The sort function actually takes a struct as the third argument. The struct has a funciont pointer for a comparison function. See this example, implement it yourself, and then try to adapt it: c++ slt sort.

I know the sort interface is clunky, but it will work if you set it up correctly. The convenience after that is very nice

dusktreader 137 Posting Whiz in Training

Double number may have 64bits length,so it has a limit on the stored value(minus 32 times, 32 times)

There is a limit, but I'd be surprised if the OP would have to worry about going larger than 1.7 * 10 ^308.

Of, course, with the big numbers you lose precision in lesser significant digits, but usually with large numbers, nobody cares about that.

dusktreader 137 Posting Whiz in Training

I've managed to get my preliminary code working! Got a vector of objects pointers now and I am able to work with the vector in my simulation. Also managed to implement the sort function, though I discovered that you need a workaround to use it if you're using a sort function that's defined in a class. I don't like the workaround, but for now it's working (posted another thread about the workaround, but got no response).

Maybe as I get more savvy with C++ I can figure out a way to code this more elegantly.

Anyway, thanks a lot to all who provided me with feedback here! Very much appreciated :)

Got lots of other questions, but I'll just post them up in separate threads. This one is case closed now I believe :)

Cheers,

Kartik

I'm curious as to what the work around was and where you posted your question.

dusktreader 137 Posting Whiz in Training

don't redirect me to a site that already made a library for this because you only wasted your time telling me that.

Here's some redirection for you: show effort

I'm feeling generous, so I'll give you a little hint.
Use doubles.

dusktreader 137 Posting Whiz in Training

I apologize for taking me so long. I was awaiting a response from my teacher. This is what I have so far.
/QUOTE]

1. You really need to use code tags. Read the posting rules. It's easier to get help if you follow the posting rules.

2. If you are trying to use char arrays to add "really big numbers", why are you using int arrays? int num1[26] is not a char array! You should probably check the requirements for this assignment. Incidentally, a char is an integer value. It has only 8 bits of data while an int has (usually) 32. So, you can do all your usual integer arithmetic using chars and save 4 times as much memory.

3. You are starting at 1 in your for loops. This means you are skipping over the first element. Arrays in c and c++ start at 0:

for( int [B]i=0[/B]; i<n; i++ ){
    //do something with i
}

4. Your loops are crazy. Sorry, that's the simple way to put it. You need to re-think your logic. You are getting a sigle character from standard input, then you are setting every element of num1 and num2 to 0 except for the first and last element of the array. The first element is being skipped (see problem #3), and the last one is being set to the input value. However, this value gets overwritten as soon as a new value is gotten from the input. Delete your loop structures and start …

dusktreader 137 Posting Whiz in Training

That's brilliant Dusktreader, thank you very much. Genius :) I will have a think about what you've said and see what I can do.

Thanks, but this is the standard math for doing these sorts of index conversions

dusktreader 137 Posting Whiz in Training

/*I am getting the following errors
free.cpp: In function 'int main()':
free.cpp:24: error: expected `;' before 'obj'
free.cpp:25: error: 'obj' was not declared in this scope
free.cpp:25: error: expected primary-expression before 'int']

free is a reserved keyword in c++ and c. You need to name your class something else.

dusktreader 137 Posting Whiz in Training

I haven't used them before, but I know a lot of people use quaternions to calculate 3 axis rotations. Apparently they compose better than using Euler angles. Have a look. Like I said, I haven't used them, but they might be what you are looking for.

dusktreader 137 Posting Whiz in Training

So the question is... how do you extract the column and row vectors using your particular representation of a matrix?

You wrote a bunch of information that didn't answer the question and then re-asked to OP's question.

OP: you can think of representing a 2D matrix in 1D as a counting operation. Basically, you count from zero to the # of elements in the column, then go back to zero and start again. This should remind you of a modulo operation, where as you increment an integer, it wraps back to 0 at the divisor. So:

6%8 == 6
7%8  == 7
8%8 == 0
9%8 == 1
10 %8 == 2

This is half of the method you would use to convert between 1D indices and 2D indices. The other half can be defined by using integer division. Integer division will basically tell you how many times you have counted up to some number ( like the # of elements in a column ).

6/8 == 0
14/8 == 1
22/8 == 2
30/8 == 3

Now, if you can combine an integer modulo opeation with an integer division operaton, you can extract 2D indices from 1D indices. I don't want to answer your question completely ( because it might be homework ), but I think this should point you in the right direction.

dusktreader 137 Posting Whiz in Training

I have decided that instead of doing these calculations on the fly, I will do a pre-processing step first that will do all my calculations for all objects at all time positions. This should relieve any need for thread-safety in these maps.

dusktreader 137 Posting Whiz in Training

In my application, i currently make many (parallel) calculations based on a time parameter. The calculation is a parametric function of time, so, each time value renders a unique solution. Currently, I have many threads that are calling the same calculation function, and the time parameters are often the same. The calculations can take some considerable amount of time.

I want to optimize by adding a hash-table like structure. So, instead of calculating and recalculating for identical times across many threads, I would prefer storing the calculation results in a hash-table keyed by the time. My application currently uses the STL for its containers, so I would like to use the map container.

Now, I know this container is not thread safe, so I am trying to devise a system to wrap the map object to ensure thread safety. I am considering two alternative methods to achieve this. Here is the (untested, uncompiled, just conceptual so far) code for the two methods:

double method0( double t, double (*calculate)(double) ){
    double result;
    omp_set_lock( &mapLock );
    if( calcMap.count(t) == 0 ){
        result = calculate(t);
        calcMap.insert( pair<double,double>( t, result ) );
    }
    else
        result = calcMap[t];
    omp_unset_lock( &mapLock );
    return result;
}

double method1( double t, double (*calculate)(double) ){
    double result;
    if( calcMap.count(t) == 0 ){
        omp_set_lock( &mapLock );
        if( calcMap.count(t) == 0 )
            calcMap.insert( pair<double,double>( t, calculate(t) ) );
        omp_unset_lock( &mapLock );
    }
    return calcMap[t];
}

Now, I think the first method should always work, because all access to …

dusktreader 137 Posting Whiz in Training

Just to be a grammar police here, but you forgot the "n" in many "for maNy people."

Thanks, i'll fix that!

dusktreader 137 Posting Whiz in Training

I would also suggest you use the switch construct. It's easy, and it works with any integer value

switch( action ) // action is some integer value
{
    case 1:  // action == 1
         cout << "Processing code for action 1" << endl;
         break;
    case 3:
         cout << "Executing commands for action 3" << endl;
        break;
    case 7;
         cout << "Doing some stuff for action 7" << endl;
        break;
    default:
         cout << "Running for all actions besides 1, 3, and 7" << endl;
         break;
}

See this website for more detail on if statements, loops, and switch statements (near the bottom) Do not use goto! It is considered bad practice in general

dusktreader 137 Posting Whiz in Training

Only good for a tree. I think you mean Permutations.

Or good for a graph. Suppose that the cities are a fully connected graph ( which it sounds like they are ), then doing a depth first traversal of the graph from each node will render every possible permutation.

dusktreader 137 Posting Whiz in Training

Displaying them in all possible unique combinations is what I'm looking for. Can you give an example of how to accomplish it?

You're asking for a solution to your homework? I'll give you a hint: Depth First Search.

dusktreader 137 Posting Whiz in Training

hi
i am trying to write a simple calculator.i have posted the code below,it works fine for one time solution. but i want the answer to be used for next calculation and also want to put a code to end the program.

1. You need some variable that will store the result.
2. You need to use a loop to keep asking for and processing input
3. You need that loop to have a termination criteria. A termination criteria is some condition that would signify that the loop should stop.

dusktreader 137 Posting Whiz in Training

google "c++ srand"

dusktreader 137 Posting Whiz in Training

I am trying to get the code to multiply two fractions then reduce them. I tried the Euclid's Algorithm without any luck. I keep getting a large number instead of a reduced one.

Well, I assure you that Euclid's Algorithm works. You may either not be implementing it correctly, or you aren't applying it correctly. Given two integers, Euclid's Algorithm will tell you their greatest common divisor. It should be obvious how this could be used to reduce two fractions.

dusktreader 137 Posting Whiz in Training

I like to use a macro for this sort of thing:

#define RAND_INT( low, high ) ( rand() % ( high - (low) + 1 ) + low )

you would put that near the beginning of your code (right after your #includes ). Then, you can simply do something like gold = RAND_INT( 10, 20 ); This would result in gold having a random value ranging from 10 to 20. You would still need to call srand at the beginning of your main before you call this function.

dusktreader 137 Posting Whiz in Training

/*I am a noob to all of this and am looking for a little help in the process of posting and getting assistance. Any at all would great*/

1. Ask your quesiont in plain english. Spell it out clearly. Don't make us try to guess what you are trying to do and what your problem is.

2. There are lots of people on here that are experts and are willing ( and sometimes eager ) to help you. They do this ( for the most part ) on a volunteer basis. So, you should be as polite as possible, and you should make it clear what you need. Nobody wants to spend a lot of time guessing what you need.

3. Read the responses that people write. I tried to tell you that Euclid's Algorithm would be very helpful for your program, but apparently you didn't read about it.

4. No one is going to fix your code or write code for you ( usually ). Many people will, however, give advice and try to steer you in the right direction.

dusktreader 137 Posting Whiz in Training

Honestly, it's almost less work to do it the way you have it there.

Maybe ( i actually disagree ), but that solution wouldn't extend very well at all.

OP: think about how you would mentally walk over a matrix visiting every element. Think about the system you use to ensure that you visit every single element. Now, think about how you could write down instructions describing how to walk the matrix. Think about how to write these instructions so that another person who has no idea of what a matrix is or what it is for could still walk over the matrix and visit every element. If you carefully and thoughtfully do that, you should see that the instructions contain two logical loops with one nested inside of the other. Try to apply the logic of those instructions in code.

dusktreader 137 Posting Whiz in Training

Hi

Currently i am using Matlab, but i need to convert the matlab code to C/C++, So that it will be sue full for a mobile application.
But the problem is i am not sure where we can use Open CV for such application.

I found this on google: http://alexkarpus.com/opencv/. Looks like using OpenCV for mobile devices is very doable.

Look at the OpenCV website, the OpenCV Yahoo User Group, and google in general for some good examples of how to use OpenCV.

Nick Evan commented: Sounds good +12
dusktreader 137 Posting Whiz in Training

Is the functionality of the code example you've provided with me essentially doing the same as the following?
someCode{}
Got that code when I googled "array of pointers to objects" ( http://www.java2s.com/Tutorial/Cpp/0180__Class/Anarrayofpointerstoobjects.htm ).

Yes, that is functionally equivalent. However, the array in this case is not dynamic at all.

Additionally, since the number of objects required is declared already before runtime, is dynamic allocation necessary? My understanding is that dynamic allocation requires more overheads right?

Doing multiple dynamic allocations ( repeated calls to the new keyword for single objects ) can introduce an overhead. However, using dynamic allocation lets you avoid the very real possibility of overflowing the stack. I would highly suggest that you use dynamic allocation that is dependent on a variable that is specified at run-time. In my opinion, it is always better to take a little bit more time to make a program flexible, because it is likely that it will need to be extended at some point in its life. For small objects on the order of 1000 to 10000 instances, I wouldn't worry about using dynamic allocation. The only time when you really take a hit on dynamic allocation is when objects are getting dynamically allocated and freed frequently within a region of code ( say, in a for loop ).

Also, once I declare objects, they all acquire properties through the constructor, which I then have to sort in ascending/descending order, based on the numerical …

dusktreader 137 Posting Whiz in Training

Thanks alot for your help.
do you have some code for this in matlab? i m new in this field. sooo please if you colud provide me some code for understanding as well i will b grateful.
regards

Sorry, I use c++ with OpenCV for this sort of thing.

dusktreader 137 Posting Whiz in Training

I'm not quite sure how to go about this though. For instance, if my class is called Particle, how do I go about setting up firstly 1000 objects of this class, and secondly pointers to each of the objects in an array/vector?

Thanks for the input,

Kartik

You can do this quite easily with classes by using dynamic memory allocation ( the new keyword in c++. So:

class Particle{
       // Internals
      public:
        Particle( double param0, double param1 );  // However you want to work it
};

int main(){
    vector<Particle*> particles;
    for( int i=0; i<1000; i++ )
        particles.push_back( new Particle( param0, param1 ) );
    return 0;
}

You could, of course, use a temporary pointer as a midway point if you need to do something with the particle before you add it to the collection. So:

int main(){
    vector<Particle*> particles;
    Particle* part;
    for( int i=0; i<1000; i++ ){
        part = new Particle( param0, param1 );
        // do stuff with particle
        particles.push_back( part );
    }
    return 0;
}

Either way, it should not be too difficult to build your collection of particles. The only thing you will need to be carefull of is clean up. Since your collection contains pointers instead of the actual objects, you have to explicitly delete each particle in the list to free the allocated memory. So:

int main(){
    vector<Particle*> particles;
    // do a bunch of stuff including adding particles to the container
    for( unsigned int i=0; i<particles.size(); i++ )
        delete particles[i];
    return 0;
}
dusktreader 137 Posting Whiz in Training

This seems to be the age old 'artificial' problem that your classes are (at least in part) fundamentally unrelated to each another, but regardless of that they have an established relationship anyway; i.e, your classes do not share a common interface - the fact that they each have a function called setParams is irrelevent, because those functions have nothing in common with each other. I get the feeling that inheritance is maybe the underlying cause of your problem rather than part of the solution.

do you have any more concrete examples of what the real classes actually are? You might be able to build in a different kind of relationship, perhaps by splitting out the data processing/behaviour elements which maybe are related, and the data elements into separate classes.

The classes are absolutely related to each other both in structure and functionality. The classes are all object detectors, and each uses a different algorithm in order to identify specific objects within an input image. The function prototypes for each class are identical, with a single exception being one constructor and the setParams function:

class DerivedDetector : public Detector{
public:
    DerivedDetector();
    DerivedDetector( const std::string& fileName );
    DerivedDetector( /* some list of params unique to each class*/ );
    void setParams( /* some list of params unique to each class*/ );
    virtual ~DerivedDetector();
    virtual void prepare();
    virtual int search( cv::Mat src, const cv::Size& minSize, const cv::Size& maxSize, std::vector<cv::Rect>& detections );
    virtual bool isValid();
    virtual bool read( CvFileStorage* fs, CvFileNode* node );
    virtual …
dusktreader 137 Posting Whiz in Training

You should also consider using a better reduction algorithm. I think you probably don't know about Euclid's Algorithm. It would be very helpful for this problem, and you would have to test every value in the interval ( 1, a*b ].

Euclid's Algorithm

dusktreader 137 Posting Whiz in Training

First of all, you need to have the image data stored in some sort of serially accessible data structure. Lets suppose that you have the image data in an array of floats.

Next, you need to scale your data to a specific range. Often, this range is the interval [0,1.0). However, some activation/squashing function combinations do better with different input ranges. It may be more appropriate to choose the (-1.0, 1.0 ) interval. Your choice of scaling method could also be significant. Often, you will want to normalize the pixel values to a specific range. The easiest approach is to scale each value by 1.0 / MaxPixelValue ( usually 1.0 / 255 ). However, it is usually better to do a min/max nomralization.

Once you have your normalized image data in a serially accessible data structure, all you need to do is step through it and assign each pixel value to an input node (or, with some ANNs, pass the array to the train/classify function).

One thing you should be sure to note: Neural nets are extremely sensitive to affine transformations of image data. So, rotations, displacements, and scalings will confuse your ANN. To combat this problem, you either need a method to correct affine transformations before classification, or you need a method to convert raw pixel data into another form that is invariant to these affine transformations.

dusktreader 137 Posting Whiz in Training

Some of your words have trailing spaces. This results in some un-fun!

Mystery Word : numerical*
Guessed letters : e,i,t,s,l,a,o,d,n,m,u,r,c,y,z,b,f,g,h,j,k,p,q,v,w,x,
Guess number : 26

Enter a letter :

I was having fun until I realized that numerical didn't fill the word. What begins with numerical and ends in one more letter? numericaly?

dusktreader 137 Posting Whiz in Training

You really should describe what your problems are in greater depth. Usually I would just make that comment and quit, but I'm waiting to see if my question gets answered soon, so I'll help

class Truck: 
			public Vehicle
			{
				bool DieselTypeStatus;	
				Truck();				
				[B]void Truck(bool);	[/B]
				~Truck();			
				void DieselTypeStatus(bool);	
				bool getDieselTypeStatus()const;
			};

1. A constructor cannot return a value. This should be Truck(bool); 2. Members of a class must have unique names. You can't have a function and a variable with the same name (DieselTypeStatus). Your implementation uses setDieselTypeStatus(bool) , so the function should be declared this way in the class specification.
3. You are declaring all members of Truck to be private (by omitting the private and public identifiers). Truck() , Truck(bool) , ~Truck() , void setDieselTypeStatus(bool) , bool getDieselTypeStatus()const should all be public

void Truck::setDieselTypeStatus(bool)
        {
            setDieselTypeStatus = false;
        }
        bool Truck::setDieselTypeStatus() const
        {
            return setDieselTypeStatus;
        }

1. The variable is DieselTypeStatus, so change these two places to reflect that.
2. This one should be getDieselTypeStatus ?
3. Shouldn't you be setting DieselTypeStatus to the argument for setDieselTypeStatus(bool)? Right now, the argument is completely ignored (and unnamed).

I fixed these problems in your code, and the program compiled and ran. Fix these mistakes, and see where it goes from there.

Really, you need to be much more careful in writing your code. Make sure you think about what you are doing on every line. Your brain should walk the path …

dusktreader 137 Posting Whiz in Training

Before you try to tackle the whole problem at once with code you are not sure of, you should try to create a 'toy' problem with only a few lines of code that uses the concepts you need to perfect.

In your case, you need to learn about how cin can be used to store data in local variables. Try to create a very simple program that accepts input using cin, and practice storing user input in a variety of different variable types.

In general, it is a good idea to build software incrementally. That is, you should build small, simple code first that uses the concepts you need, verify that it works and that you understand the concept, and then extend the concepts to your problem.

Look at this example to get a better idea of how to handle input:
http://www.cplusplus.com/doc/tutorial/basic_io/

dusktreader 137 Posting Whiz in Training

I have a class hierarchy in which the base class is abstract. Each derived class has a set of private members which describe parameters that control how the class processes data. I want to enforce implementation of a setParams() function across all derived classes. However, because the parameters for each derived class are unique in number and type to that class, it doesn't seem like creating a pure virtual function will work due to the argument missmatch. Here is an outline of my hierarchy:

class Base{
    public:    
    // Constructor, destructor, etc...
    virtual void setParams() = 0;  // This is the function for I wish to enforce implemenation
}

class DerivedA{
    private:
        int param0;
        double param1;
        char param2;
    public:
    // Internals
  
    // I know this won't work
    virtual void setParams( int param0, double param1, char param2 );
}

class DerivedB{
    private:
        double param0;
        double param1;
    public:
    // Internals
  
    // I know this won't work
    virtual void setParams( double param0, double param1 );
}

I would like to avoid passing parameters in numerical arrays, if possible, because I would prefer the argumets of the setParams function to be descriptive for each class ( mostly for intellisense style lookup ).

Does anyone know if such a construct exists in the c++ spec, and if so, how can I do this?

Thanks