<cracking knuckles>
Ok, let's dig into this.

[QUOTE=prvnkmr449;1328943]As I understand your problem is to minimize this highly nested loop which print the value of 12 variable.
[/quote]
You should note that the program calls two functions [icode]a()[/icode] and [icode]b()[/icode]. So, it is doing more than just printing out the values of variables. At any rate, yes, this seems to be the main push of the program.

[QUOTE=prvnkmr449;1328943]
Here is my very short program for that but very deep logic is behind that please try to understand the logic behind this first take look too code
[/quote]

1. Program isn't that short
2. Logic isn't that deep
3. Maybe you should present your algorithm in clearer terms instead of slapping the reader with convoluted pure C code and expecting them to follow

[CODE]
long double n_digit= 5;//0,1,2
long double n_var =4;//x,y,z
long double dif_com =pow( n_digit,n_var);
[/code]
When I got here, I knew we were in for a doozy. I notice that you are calculating the number all possible combination of n-digit numbers in a b-based numbering system. First of all, this is not necessary. Secondly, it is wrong. Let's investigate why

First look at a section of the OP's code:
[code]
for(int i=5;i>0;i--)
{
for(int j=5;j>0;j--)
{
if(j<=i){
[/code]

We can see clearly that the nested logic within the for loop iterating j is only executed [I]when j is less than or equal to i[/I]. This logic is repeated for each loop. Obviously, then, we aren't interested in [B]every possible[/B] ...

Akill10 commented: well said! +1

I forgot to mention that you use the above code for your application by subsituting an array (or vector, etc) of ints for the loop control variables. So:

[icode]

i j k ... t
| | | |
v v v v
[ 4 4 4 ... 2 ]
[/icode]

What it appears to me is that you have a specialized base-5 numbering system. It is specialized in that it has rules that dictate how you count down in this system. You could make this system very extensible and have it work with an arbitrary number of digits and arbitrary numerical base. The best way to do this is to develop some rules:

• A number in this system may have an arbitrary numerical base b
• A number in this system may have an arbitrary number of digits n
• No digit at index i in the number may be larger than the digit at index i-1

I have implemented a system like this before. I had to create my own specialized numbering system for this problem: [url]http://www.daniweb.com/forums/thread280248.html[/url]
Your challenge is similar.

Try implementing something like this:

[icode]
b = 5 # 5 is arbitrarily chosen. this could be any number
n = 24 # again, 24 is arbitrary
num = array[n]
for i from 0 to n:
num[i] = b - 1 # Set all numerals to b-1

while num > 0: # Terminate when the leftmost digit is 0.
[COLOR="Green"]do something with num[/COLOR] # All the rest of the code is counting down
j = n - 1
num[j] -= 1 # Decrement the right-most digit
while num[j] < 0: # If the digit goes below 0, you have to decrement the digit to the left
j -= 1
num[j] -= 1
while j < n - ...

[QUOTE=Fbody;1319894]On this site, a "space" or 2 is sufficient indent. A [I]TAB[/I] is too big.[/QUOTE]

Actually, you shouldn't have actual tabs in your code. That is my opinion, and it is right. Code editors use monospace fonts ( at least they should, for the love of Turing ). Tabs are used by word processors to gurantee alignment of [I]non[/I]-monospace fonts. As far as I know, all editors provide an option to replace tabs with some fixed number of spaces. You should use this option. My personal preference is 4 spaces for each indentation level.

[QUOTE=Kanoisa;1311400]I would in hindsight agree with dusktreader, however make one final suggestion.

Instead of a constant sized array of data consider using stl vectors or llists which let you read any amount of input without knowing its size first. If you know the size of input will never change i guess the above way is fine but its just a thought.[/QUOTE]

I completely agree. This code could be improved greatly by using the [B]Standard Template Library[/B].

However, it is obvious that this person is studying computer science. Often teachers/professors insist on students using [I]old[/I] programming paradigms that are carry-overs from C. To me, this practice is asinine, because many programmers continue to use these methods beyond the classroom when there are simpler, cleaner, and more robust ways to implement the same functionality. It is especially annoying when the preferred method [I]is [B]native[/B] to the C++ language![/I]

So, I didn't want to confuse the OP. However, if you are listening, dear OP, please read up on the use of std::vector and the other joys of the c++ standard template library. I promise you that once you embrace the STL, your code will improve and you'll be spending less time bounds checking and searching for seg faults and more time producing good code.

[QUOTE=mike42intn;1310686]

[CODE]
char sentance;

int i = 0;

srand((unsigned)time(NULL));
for( i = 0; i <= 20; i++)
{
strcat_s(sentance, article[rand()%5]);
strcat_s(sentance,noun[rand()%5]);
strcat_s(sentance,verb[rand()%5]);
strcat_s(sentance,preposition[rand()%5]);
strcat_s(sentance,article[rand()%5]);
printf("\n\n%s\n\n'", sentance);
}
} [/CODE][/QUOTE]

My guess is that you are overrunning your sentence array. First, you should make it larger. 40 characters probably won't consistently be enough. Secondly, you need to clear your sentence variable right after you pring it each time. Using the strcat() function, you are just adding more and more words to the same sentence. You'll run out of your 40 characters rather quickly this way!

I wouldn't use getline for this. If you do so, you must take responsibility for tokenizing the lines and converting string data. The iostream library can do this automatically for you, so using ifstream and the >> operator is correct.

My guess is that you are reading all of the data into the same variables over and over.

this code:
[code]
while( fin && !fin.eof() )
{
Node * temp = new Node;
char first ;
char last ;
int acctnumber;
double balance;
//char notes ;
char created ;
char modified ;
fin >> first >> last >> acctnumber >> balance >> created >> modified;
}
[/code]
Doesn't do anything with the data it has read. It simply goes to the next iteration of the loop and reads that data into the same variables as the previous loop.

My guess is that your output is the last record in the file repeated so many times.

My suggestion for you would be to create an array of structs containing the data read from file. That way, you can store all the data you have read without overwriting anything.

Something [B]similar[/B] to this should work for you:

[code]

include <iostream>
include <fstream>

using namespace std;

struct MyData
{
char someString;
int someInteger;
double someReal;
};

void myReadingFunction( ifstream& fin, MyData data[], int& count )
{
count = 0;
while( !fin.eof() )
{
fin >> data[count].someString

data[count].someInteger
data[count].someReal;
count++;
}
}

void myPrintingFunction( MyData data[], int count )
{
for( int ...

You could do this in an even cleaner fashion by using references. If you use const references, you can pass in values that have not been saved in a variable:

[code]

include <iostream>
include <vector>

using namespace std;

const double& max( const double& a, const double& b )
{
return a > b ? a : b;
}

int main()
{
cout << max( 5.0, 7.0 ) << endl;
double a = 13.0;
double b = 11.0;
double c = max( a, b );
cout << c << endl;
return 0;
}
[/code]

My friend, you are suffering through pointer hell. The best way to avoid this is to use the standard template library. Vectors are infinitely nicer than dynamically allocated arrays of pointers. In order to understand your code, I had to work through it. In the process, i utilized the standard template library. The code worked almost immediately after eliminating compiler errors. Here it is:

[code]

include <iostream>
include <vector>

class neuron
{
public:
// Other members and constructors omitted

``````std::vector<neuron*> connections;

void connect( const std::vector<neuron*>& inconnections )
{
connections.clear();
for( unsigned int i=0; i<inconnections.size(); i++ )
{
if( this == inconnections[i] )
continue;
connections.push_back( inconnections[i] );
}
}

//Printing functions ommitted``````

};

class network
{
public:
std::vector<neuron*> neurons;

``````neuron*& slot( int i, int j )
{
return neurons[ i * w + j ];
}

network( int w, int h ): w(w), h(h)
{
neurons = std::vector<neuron*>( w * h, NULL );
for( int i=0; i<h; i++ )
{
for( int j=0; j<w; j++ )
{
slot( i, j ) = new neuron( i, j );
}
}
for( unsigned int i=0; i<neurons.size(); i++ )
neurons[i]->connect( neurons );
}

// Destructor and printing functions ommitted``````

};

using namespace std;

int main()
{
network net(2,2);
net.printNetwork();
return 0;
}

[/code]
Outut:
[icode]
Network structure:

My name is: [0,0]
I am connected to:
0,1
1,0
1,1
My name is: [0,1]
I am connected to:
0,0
1,0
1,1
My name is: [1,0]
I am connected to:
0,0
0,1
1,1
My name is: ...

Your solution is not recursive. Recursive logic is very elegant and powerful, and for algorithm junkies like myself, completely awesome. The trick is understanding how recursion works. I'll use your reverse problem as an example.

Suppose we want to reverse the string "Hello". Well, the fundamental problem is switching the location of each letter. The first step would be putting "H" at the end of the string:

[icode]
Hello
|____
v
elloH
[/icode]

Well, that's all fine and good, but if we continue to use that logic within the same fuction, we will just get the original string back:

[icode]
elloH
|____
v
lloHe

lloH
|____
v
loHel
[/icode]

The key is to do this swap at different levels:

[icode]
Hello
|____
v
elloH

ello [H]
|___
v
lloe [H]

llo [eH]
|__
v
lol [eH]

lo [leH]
|__
v
ol [leH]

o
|
v
o [lleH]
[/icode]

This can be done rather easily with recursion. The trick is to understand how to order your function so that the correct logic is used. Here's the pseudo code for the recursive reverse function:

[icode]
string reverseR( string target ):
if length( target ) == 1: # if the target is only one character long
return target # there is no need to reverse it
character first := target # remove first letter and save it for later
string newTarget := target[1:end] # now, reverse the rest of the letters
newTarget := reverseR( newTarget ) # the remaining letters have been reversed ...

The problem here is that you are declaring an instance of a variable inside of your header file. You are essentially making [B]messages[/B] or [B]channels[/B] global variables. This would be fine [I]if the header was only included by a single source file[/I]. Here's what's happening. Every source file that includes your header file will get its own [I]seperate[/I] variable in the global scope with the given name. This works fine for [I]compiling[/I], as each object file doesn't care what is defined in other object files. However, when you link the objects together, the linker sees multiple variables with the same name in the same scope. This isn't legal, so it fails.

As a rule, it is bad practice to use global variables, so you're going down that wrong road. You should consider using a class with accessor functions for getting to the data. In any case, those variables should be declared within the scope of a source file.

I also notice that you used "using namespace std;" in your header file. This is also bad practice. Prefix all of your stl types with [B]std::[/B] in a header file, and only use "using namespace std;" in a source file.

Please post your input file.

I think you are getting the value of an unitialized variable. In c and c++, when you declare a variable like:
[code]
int someVariable;
[/code]
The program is simply reserving an int sized memory block somewhere on the stack. Please note, the program only [I]reserves[/I] the spot, it doesn't do anything with the memory. So, whatever data resided there before you declared the variable will become the value of the variable. You have to explicitly set the values of your variables if you want them to be fully intialized:
[code]
int someVariable = 0;
[/code]
I would try this with your variables and run it again. I think you'll see that the huge number is gone.

You should also check the values that you are reading in as a debugging step. This step can be removed later when you are sure that your program is functioning correctly. After you read in the three values, print their values to the screen:

[code]
inFile >> var0 >> var1 >> var2;
cout << "var0" << var0 << endl;
cout << "var1" << var1 << endl;
cout << "var2" << var2 << endl;
[/code]
That way, you can verify what is actually being read by your program. I suspect that whatever is in your input file is being read into none, the first, or the first two variables and at least one of the variables is not getting any input. Add the debugging couts and see what happens.

The problem is (most likely) that you have to define a template function in the same file where it is declared. For a good over-view and specifics on the multi-file problem, see [URL="

You need to first realize that there is no [][] operator. In fact whenever you see matrix2D[][] or matrix3D[][][] or matrixND[][]...[], you are actually seeing multiple nested calls on the [] operator.

Consider the case for a 2D matrix. If you declare the matrix like so:

``````int rows = 5;
int cols = 7;
int** myMatrix = new int*[rows];
for( int i=0; i<rows; i++ )
myMatrix[i] = new int[cols];``````

You are actually first declaring an array of int pointers. Each one of these int pointers is then pointing at another array of ints. The way this lies in memory can be looked at like this

``````array[ *, *, * ]
|  |  |
|  |  |---> array[ i, i, i ]
|  |
|  |------> array[ i, i, i ]
|
|---------> array[ i, i, i ]``````

So, when you are accessing an element of a Matrix like this:

``myMatrix;``

You are actually first accessing the element of the pointer array at position [COLOR="Red"]1[/COLOR], and then accessing the element of the nested int array at position 2:

``````          1
|
array[ *, *, * ]
|  |  |
|  |  |---> array[ i, i, i ]
|  |
|  |------> array[ i, i, i ]
|                        |
|                        2
|
|---------> array[ i, i, i ]``````

So, you can't really design a custom class that can in and of itself process the nested [] operators ( [][] ). You can, however, overload the [] or () operator to behave like this: ...

You need to declare the static member outside of the class definition like so

[code]

ifndef DIE_H
define DIE_H
include "aRandomNumberGenerator.h"

class aDie
{
public:
aDie();
double roll();
void seed (int s);
int inputSeed();
~aDie();

``````private:
static aRandomNumberGenerator gen;``````

};

endif
include <iostream>
include "aDie.h"
include <cmath>

using namespace std;

[COLOR="Red"]aRandomNumberGenerator aDie::gen;[/COLOR]
// or
// aRandomNumberGenerator aDie::gen( ... );
// or
// aRandomNumberGenerator aDie::gen = new aRandomNumberGenerator( ... );

aDie::aDie()
{

}

double aDie::roll()
{
return (fmod(gen.generate(), 6) + 1);
}

void aDie::seed(int s)
{
gen.setSeed(s);
}

int aDie::inputSeed()
{
int value;

``````cout << "Please enter a seed value: ";
cin >> value;

seed(value);

return value;``````

}

aDie::~aDie()
{
//Destructor does nothing in this case.
}
[/code]

[QUOTE=Sandhya212;1224739]Hi,

I have code as follows wherein I pass a 2D array to a function and want to receive this array with its contents tripled.

The error I get is 'error: cannot convert 'int (*)' to 'int**' in return'.
I was able to send and receive a 1D array using 'pass by value' but for 2D I hit this error. Please advice.[/QUOTE]

The most obvious solution is to [I]not[/I] return anything from the function. Since the array is passed to the triple function by reference, there is no need to return its address. You can simply pass the array to the function, modify it in place in the function, and when the function returns, the array will have been modified and its address will be the same. There is absolutely no need to return a pointer from the function. For example:

[code]

include <iostream>

using namespace std;

int modify( int arr )
{
for( int i=0; i<4; i++ )
arr[i] += 1;
return (int
)(arr);
}

int main()
{
int origArr;
memset( origArr, 0, 4 sizeof(int) ); // fill with 0's
int
newPtr = modify( origArr ); // Now it is filled with 1's
cout << ( newPtr == origArr ) << endl; // The pointer references the same location as the original array
return 0;
}
[/code]

You could instead simply do this:
[code]

include <iostream>

using namespace std;

void modify( int arr )
{
for( int i=0; i<4; i++ )
arr[i] += 1;
}

int main()
{
int ...

[QUOTE=caffeine;1176222]Oh, for the love of Darwin.

Thank you for restoring my sanity (and sorry for the brain fart).[/QUOTE]

Glad to help.

caffeine commented: Thank you for being patient with my stupid mistake! +1

Are you not allowed to use cin to get whole strings from an input file?

[icode] cin >> someString; [/icode]

If you are, you could fetch an entire string at a time and process each string individually.

Try including <sstream> in SafeArrayUtil.h

I have a bunch of code that looks like:

``````// Local block scope
{
ostringstream  ostr;
ostr.fixed;
ostr.precision(2);
ostr.width(20);
ostr << foo->bar[trno];
SafeArrayPut2D( retArray, 3, i, (void *) ostr.str().c_str() );
}
{
ostringstream  ostr;
ostr.fixed;
ostr.precision(4);
ostr.width(22);
ostr << foo->foobar[trno];
SafeArrayPut2D( retArray, 4, i, (void *) ostr.str().c_str() );
}``````

So I wanted to write a function to abbreviate the process. Here's what I did. In the header file:

``void ostreamStringHelper( ostringstream& oss, streamsize prec, streamsize width );``

In the cpp file:

``````void ostreamStringHelper( ostringstream& oss, streamsize prec, streamsize width )
{
oss.fixed;
oss.precision(prec);
oss.width(width);
}``````

However, it's giving me errors:

``````1>Compiling...
1>SafeArrayUtil.cpp
1>c:\safearrayutil.cpp(32) : error C2027: use of undefined type 'std::basic_ostringstream<_Elem,_Traits,_Alloc>'
1>        with
1>        [
1>            _Elem=char,
1>            _Traits=std::char_traits<char>,
1>            _Alloc=std::allocator<char>
1>        ]
1>c:\safearrayutil.cpp(32) : error C2228: left of '.fixed' must have class/struct/union
1>c:\projects\cashflow\trancheinfodll\safearrayutil.cpp(33) : error ``````

I don't understand --- what exactly is the problem with the ostreamStringHelper() function? oss is a reference to a class, not a pointer; why is the syntax invalid?

Thanks!

It's hard to say, when you haven't given enough source code to determine what line the error is actually coming from. I implemented a quick demo:

``````void helper( ostringstream& oss, streamsize prec, streamsize width )
{
oss.fixed;
oss.precision( prec );
oss.width( width );
}

int main(int argc, char *argv[])
{
ostringstream ostr;
helper( ostr, 3, 6 );
return 0;
}``````

This compiled and ran fine for me using g++. Post the offending line or all of the offending ...

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:

[icode]

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

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

For row major matrices:
[icode]
row = index / width;
col = index % width;
[/icode]

For column-major indices
[icode]
row = index % height;
col = index / height;
[/icode]

Hope this helps!

This sounds like a computer vision problem. This [I]is[/I] an ambitious project, though not at all impossible. Like @tetron suggested, you should do [I]a lot[/I] of reading first. Then you might want to check out [URL="

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

[QUOTE=Fbody;1142085]Did you even read that link you posted? It doesn't [B][U]have to[/U][/B] 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.[/QUOTE]

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

Fbody commented: a point for admitting your mistake +1

[QUOTE=TheWolverine;1142070]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.[/QUOTE]

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: [URL="

[QUOTE=sexyzebra19;1139772]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.[/QUOTE]
Thanks, but this is the standard math for doing these sorts of index conversions

[QUOTE=n1337;1139713]
So the question is... how do you extract the column and row vectors using your particular representation of a matrix?[/QUOTE]

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:
[icode]
6%8 == 6
7%8 == 7
8%8 == 0
9%8 == 1
10 %8 == 2
[/icode]
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 ).
[icode]
6/8 == 0
14/8 == 1
22/8 == 2
30/8 == 3
[/icode]
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.

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 values of the ...

[QUOTE=TheWolverine;1133696]
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[/QUOTE]

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

[code]
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;
}
[/code]

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:

[code]
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;
}
[/code]

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 [B]delete[/B] each particle in the list to free the allocated memory. So:

[code]
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]; ...

[QUOTE=moein_soltani;1132232]I have another problem in implemention of Huffman code..
in some file there are chararacters that stop the reading of the chars from file if we put flag on default and if we put flag on binary we face a new problem.. in this case for example "Enter" read by get() translate '13' instead of 10 ... what can i do to solve this problem...
tnx[/QUOTE]

Well, I'm not sure exactly what you are asking here. If you are confused about processing binary files, this [URL="