dusktreader 137 Posting Whiz in Training

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

As I understand your problem is to minimize this highly nested loop which print the value of 12 variable.

You should note that the program calls two functions a() and b() . 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.

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

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

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);

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:

for(int i=5;i>0;i--)
  {
    for(int j=5;j>0;j--)
    {
    if(j<=i){

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

Akill10 commented: well said! +1
dusktreader 137 Posting Whiz in Training

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:

i  j  k ... t
  |  |  |     |
  v  v  v     v
[ 4  4  4 ... 2 ]
dusktreader 137 Posting Whiz in Training

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: http://www.daniweb.com/forums/thread280248.html
Your challenge is similar.

Try implementing something like this:

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] > 0:          # Terminate when the leftmost digit is 0.
    do something with num  # 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 …
dusktreader 137 Posting Whiz in Training

On this site, a "space" or 2 is sufficient indent. A TAB is too big.

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 non-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.

dusktreader 137 Posting Whiz in Training

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.

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

However, it is obvious that this person is studying computer science. Often teachers/professors insist on students using old 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 is native to the C++ language!

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.

dusktreader 137 Posting Whiz in Training
char sentance[40];

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);
}
}

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!

dusktreader 137 Posting Whiz in Training

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:

while( fin && !fin.eof() )
{
    Node * temp = new Node;
    char first [100];
    char last [100];
    int acctnumber;
    double balance;
    //char notes [100];
    char created [80];
    char modified [80];
    fin >> first >> last >> acctnumber >> balance >> created >> modified;
}

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 similar to this should work for you:

#include <iostream>
#include <fstream>

using namespace std;

struct MyData
{
    char   someString[100];
    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 …
dusktreader 137 Posting Whiz in Training

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:

#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;
}
dusktreader 137 Posting Whiz in Training

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:

#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;
}

Outut:

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: [1,1] …
dusktreader 137 Posting Whiz in Training

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:

Hello
|____
     v
 elloH

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:

elloH
|____
     v
 lloHe

lloH
|____
     v
 loHel

The key is to do this swap at different levels:

Hello
|____
     v
 elloH

ello   [H]
|___
    v
 lloe  [H]

llo   [eH]
|__
   v
 lol  [eH]

lo   [leH]
|__
   v
  ol  [leH]

o
|
v
o [lleH]

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:

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[0]       # 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
    string result …
dusktreader 137 Posting Whiz in Training

The problem here is that you are declaring an instance of a variable inside of your header file. You are essentially making messages or channels global variables. This would be fine if the header was only included by a single source file. Here's what's happening. Every source file that includes your header file will get its own seperate variable in the global scope with the given name. This works fine for compiling, 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 std:: in a header file, and only use "using namespace std;" in a source file.

dusktreader 137 Posting Whiz in Training

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:

int someVariable;

The program is simply reserving an int sized memory block somewhere on the stack. Please note, the program only reserves 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:

int someVariable = 0;

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:

inFile >> var0 >> var1 >> var2;
cout << "var0" << var0 << endl;
cout << "var1" << var1 << endl;
cout << "var2" << var2 << endl;

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.

dusktreader 137 Posting Whiz in Training

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 this.

So, you need to move your implementation of the split2 function to your header file. I know this will be ugly, but it's the only way to make it work well. You'll notice that many projects that use temlate classes and functions make use of a .hpp extension for header files with template implementations. This gives an indication that the header will contain both function declarations and definitions.

dusktreader 137 Posting Whiz in Training

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[1][2];

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 …

dusktreader 137 Posting Whiz in Training

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

#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;

aRandomNumberGenerator aDie::gen;
// 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.
}
dusktreader 137 Posting Whiz in Training

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 (*)[4]' 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.

The most obvious solution is to not 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:

#include <iostream>
using namespace std;

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

int main()
{
    int origArr[4];
    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;
}

You could instead simply do this:

#include <iostream>
using namespace std;

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

int main()
{
    int …
dusktreader 137 Posting Whiz in Training

Oh, for the love of Darwin.

Thank you for restoring my sanity (and sorry for the brain fart).

Glad to help.

caffeine commented: Thank you for being patient with my stupid mistake! +1
dusktreader 137 Posting Whiz in Training

Are you not allowed to use cin to get whole strings from an input file? cin >> someString; If you are, you could fetch an entire string at a time and process each string individually.

dusktreader 137 Posting Whiz in Training

Try including <sstream> in SafeArrayUtil.h

dusktreader 137 Posting Whiz in Training

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 …

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

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

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

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

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

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

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

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

Well, I'm not sure exactly what you are asking here. If you are confused about processing binary files, this website might help you out ( just scroll down to the binary files section). If you post the code that processes the file and its exact output, that would help.

dusktreader 137 Posting Whiz in Training

Tnx so much for your help,if we change the code in this way :
byte = byte | ( bits << 7-i );
then we protect the order of byte :d

It depends on byte-ordering. Most modern architectures use a little-endian byte ordering, which means that the least significant bit is on the far right.

1 0 0 1 1 0 1
            ^
            |
           LSB

However, in arrays, we usually think of the element with the lowest order as being on the far left ( at offset 0 )

[1, 0, 1, 1, 0, 0, 1]
 ^
 |
 Lowest Order Element

You should think long and hard about what convention makes the most sense to you. There is no convention that is truly more correct ( though many would fiercely debate that ), however, you should make sure that you use a consistent convention to avoid confusion.

dusktreader 137 Posting Whiz in Training

any help

Sum
Variance
Perhaps try to help yourself some. There is this really great resource for programmers to find information to help solve their problems. It's called google.

Salem commented: Nice +19
dusktreader 137 Posting Whiz in Training

I do want to setup my environment such that there is a possibility of adding attributes in the future, so from that perspective it seems that using a class might not be a bad idea.

You should probably spring for some type of object in this case. Though, you might find it more suitable to use a struct for your code. Struct objects don't need a constructor (though you can give them one) and all of their members are public, so access is simpler. Of course, you can specify a class with no constructor and all public members, but what would be the point?

It is true that I need flexibility to scale up/down the system easily, so if this is an advantage of vectors it would make sense in that case for me to make use of them.
...
The issue that I really have with arrays now I guess, is that when two particles collide in my simulations, they are reduced to one. Since the particles are basically indexed by the row number in the array, this means eliminating a row, which means shifting a whole lot of data up and down the array. I am worried that this might be a weak way of programming as lead to simple errors. With a unique identifier to the objects which is not linked to the row number in the array e.g., a pointer to the object, it is my understanding that I would be eliminating this …

dusktreader 137 Posting Whiz in Training

Hi guys..
In the huffman algorithm I have made an output file contain 0 and 1..
how can I say to compiler that these 1 and zero are bit no Byte.
and how can i make the real Huffman output that its size is lesser than the initial file,
What is the huffman output?
tnx.

You can't output a single bit. The smallest amount of data that can be written to any storage ( register, cache, ram, HD ) is a byte. If you want to write individual bits, you need to first package them in bytes. So, take your 8 bits, use the left shift operator ( << ) to move the bits to the correct offest, then use a bitwise or ( || ) to combine them into a single byte.

char bits[8] = { 1, 1, 0, 0, 1, 1, 0, 1 };
char byte = 0;
for( int i=0; i<8; i++ )
    byte = byte | ( bits[i] << i );

Don't sweat the "char" type. It's simply an 8 bit integer. Note that the order of bits in the array is "graphically" reversed, so the least significant bit is actually the first item in the array. So, the byte will actually equal the binary value 10110011.

Good luck

dusktreader 137 Posting Whiz in Training

We can't use the optimizer (managerial decision, because people don't know how to use volatile, a different discussion). This is the first time I've ever seen this and I'm interested in any reasoning why we shouldn't just remove it to eliminate code bloat.

It sounds like you might be doing some parallel work here, perhaps. "Guaranteeing" the state of a register also sounds like some sort of a hack to avoid a race condition, perhaps. In serial code, the !!someVar should have no logical effect (especially in the case of native types where, regardless of the type, it's underlying bits are just getting flipped twice). For some reason, this idea is ringing a bell, though I can't place it.

Still, it seems like a hack no matter what. Ensuring thread safety should always be done explicitly using thread-safe constructs provided by the language for that specific purpose.

I would suggest that you create some unit tests for a piece of code using this convention and assure yourself that double negating a byte is indeed semantically null.

dusktreader 137 Posting Whiz in Training

You need to use virtual functions:

Class Base{
     int val;
    ....
     virtual int doIt(){
          return val;
    }
};

Class Derived: public Base{
    ....
    virtual int doIt(){
        return val + val;
    }
}

Look up virtual functions and do some reading. Virtual functions are important and a powerful part of c++

dusktreader 137 Posting Whiz in Training

One more note on the rotate function:

Because the bitshift operators can take negative numers as the rvalue aruments, there is not really a need for two macros. You can simply use a negative index to rotate in the opposite direction:

#include <iostream>
#include <climits>

#define UINT_BITS ( CHAR_BIT * sizeof(unsigned int) )
#define rotateleft(x,n)  ( (x << n) | ( x >> (UINT_BITS - n) ) )
#define rotateright(x,n) ( (x >> n) | ( x << (UINT_BITS - n) ) )

using namespace std;

int main()
{
   unsigned int value = 123;
   unsigned int a = rotateleft(value, 7);
   cout << "after rotate left: " << a << endl;
   a = rotateright(value, -7);
   cout << "after negative rotate right: " << a << endl;
   return 0;
}

output"

after rotate left: 15744
after negative rotate right: 15744

Of course, there is no harm in having both declared, in fact, it may improve readability to have both. I just felt compelled to but in and add the extra info.

dusktreader 137 Posting Whiz in Training

If those variables are truly defined externally, you should really uncomment line 24 & 25. Declaring an extern variable isn't helpful if the declaration is in a comment.

dusktreader 137 Posting Whiz in Training

Using the standard fstream libraries should enable you to read from a large file just fine. Here's some example code that compiles and works for parsing a 5.3 GB file I made just for this experiment

#include <fstream>

using namespace std;

int main(int argc, char *argv[]){
    ifstream ifile( "op.txt" );
    string container;
    char linebuffer[400];
    while( !ifile.eof() ){
        while( container.size() < 1048576 && !ifile.eof() ){
            ifile.getline( linebuffer, 400 );
            container.append( linebuffer );
        }
        // Do something with container holding at most 1MB of string data
        container.clear();
    }
    ifile.close();
    return 0;
}

Notice that you have to use a char* buffer for getline(). This is trivial, though, and you can append that char array to the end of your container string. You should be able to parse the data line by line without putting it into a storage string. However, since this is what you asked for, I've included it. Try this out and see how it works for you.

dusktreader 137 Posting Whiz in Training

Now the thing is that, I cannot tell all the time what my destination buffer size is, in that case, what if the source buffer was larger, and what if it was smaller, what will happen to the remaining "empty" space in my destination buffer?

If you don't know how much space you have available in your destination buffer, you are in big trouble. There are no protections with either strcpy or strncpy, and the program using strcpy or strncpy will happily march off the end of a buffer that is to small. So, if you have a buffer of unknown size, you can never safely copy data into it. You have to establish some way to be sure of your buffer size, or your code will be a ticking time bomb.

dusktreader 137 Posting Whiz in Training

Hi,

I am a newbie to C++ (and programming in general)

Since you are new, and have a fresh, open mind, I would recommend that you start using the Standard Template Library now. This library is powerful, helpful, and relatively easy to learn, and it works in all c++ compilers. If you are using a C compiler, you're out of luck.

Anyway, the STL provides a string object that is so much nicer than c character arrays. Here's how you could apply strings to a couple of your examples

using namespace std;
string fOutMsg = "03DS2";

The string object has lots of constructors that make it easy to set it to other strings and character arrays.

string fPpn( 32, ' '  );

You can initialize the string to be a specific character repeated n times

And here's how you can do something like srtncpy:

string superString = "0123456789";
string subString0( superString, 0, 5 );   // Will result in "01234"
string subString1( superString, 2, 5 ); // Will result in "23456"
string subString2( superString, 5, 20 ); // Will result in "56789"

Strings are relatively smart. They know how long they are, so a copy won't try to get data after the end of the string. They also have lots of methods for manipulation back and forth. If you need to convert between numeric values and strings, you can use a stringstream object in a functions like these (i wrote …

dusktreader 137 Posting Whiz in Training
unsigned int size(1073741824); //orig pos_type
//....
//read in 1 Gig file
std::ifstream fin(file_name.c_str(),std::ios::binary); // also used in

I'm not sure why you are using a binary fstream to read text data. It seems like you are causing yourself some extra pain by doing this. If you are really just parsing xml, why not use a standard ascii fstream? Also, To manage/query file sizes, you should use stat or some similar system call to get the file size.
limit.

I would like to process the file line by line eventually but first I want to simply chop it on a single xml tag.

It's actually very easy to parse line by line. If you use an ascii file stream, you can be confident that each line could be easily converted to a string object for parsing.

I also am not sure how to access just a pointer for the file start of data and then iterate char by char, which is why I wanted to use a container

Again, if you use an ascii ifstream, this is trivial. You can simply use the ifstream::get( char& c ) to extract a single character from the file.

So, I recommend you do this:
1. Use stat to query the size of the file for checks and safety
2. Open the ifstream not as ios::binary but regular old ascii ifstream::in
3. If you want to parse a section of the file at a time by converting …

dusktreader 137 Posting Whiz in Training

1. Post the code (at least some of it) so we can get a better idea of what's going on.
2. Why don't you use an XML library to parse the code. There are hundreds of XML libraries out there. Such libraries can save you a ton of work and they are usually very efficient.
3. Why are you trying to read the entire file at once? Couldn't you process line by line, and not have to worry about overflows at all?

dusktreader 137 Posting Whiz in Training

I have a weird problem with destructors. My code works in older machines with g++-2.95, g++-3.3, g++-4.0, g++-4.0.1 and not in my machine with g++-4.4.1. Do you know why? Here I show a small example that reproduces the error (in my machine):

#include <iostream>
class Matrix{
  public:
    Matrix(){};
    Matrix(int nin);
    ~Matrix();
    int Set();
  private:
    int n;
    double * data;
};

Matrix::Matrix(int nin){
  n = nin;
  data = new double[n];
  std::cout << "Constructor  " << data << std::endl;
}
Matrix::~Matrix(){
  std::cout << "Destructor  " << data << std::endl;
  delete [] data; data = NULL;
  std::cout << "End destructor  " << data << std::endl;
}
int Matrix::Set(){
  for (int i=0;i<n;i++){
    data[i*n+i] = 1.;
  }
}


int main(){
  Matrix A(50);
  A.Set();
  std::cout << "Finished normally" << std::endl;
}

Thanks in advance

Well, to start, your set function is wild!

for (int i=0;i<n;i++){
    data[[B]i*n+i[/B]] = 1.;
  }

Suppose your matrix was initialized with 50 elements. At the 38th iteration of your loop, you would be trying to access the 1938th element of the array. This obviously should break something, and that's probably where you're getting a "double free or corruption." I don't understand why you aren't accessing your items like this:

for (int i=0;i<n;i++){
    data[[B]i[/B]] = 1.0;
  }
}

Try to fix that first, and then see what happens.

dusktreader 137 Posting Whiz in Training

You have some obvious problems that need correcting:

Problem 1:

template <class T>
T min(vector<T> a)
{

Don't use the name "min". There is already min and max functions in the standard template library, and you shouldn't override these. Use something like vectorMin(), or vMin()

Problem 2:

T min = a[0];

This is no good. The function is named min, so this variable's name needs to change. Perhaps use minimum?

Problem 3:

vector<T>::iterator it;

    for( it = a.begin(); it!=a.end(); ++it)
    {

For the vector container class, iterators are not necessary for looping over the contents. They are important for the list containers (and others) because the members of a std::list are not stored in adjacent memory. For vectors, however, the data is stored just like an array so this:

for( int i=0; i<(int)a.size(); i++ ){
     doSomething( a[i] );
}

is just as fast and much easier to code / read. Using an iterator is not wrong, but it is uneccesary extra work.

Problem 4:

if((*it)<a[i++])
            min = *it;

The index to your maximum value is getting changed every time the if statement executs. So, your maximum will shift, and weird behavior will appear. You should only keep track of the index of the maximum value if you really need it.

I recommend you re-write this in a simpler form such as:

template <class T>
T vMin( const vector<T>& v ){
    T minimum = v[0];
    for( int i=1; i<(int)v.size(); i++ …
dusktreader 137 Posting Whiz in Training

Ok nevermind i thought i had this going right and im getting a funny number as an answer to the standard deviation. heres the code got so far

double findStdDev(double x1, double x2, double x3, double x4, double x5,double x)
                 
{
double sDev;

sDev=sqrt((x1-pow(x,2))+(x2-pow(x,2))+(x3-pow(x,2))+(x4-pow(x,2))+(x5-pow(x,2))/5);
return sDev; 
	
}

in your calculation, you need to change
( xN - pow(x,2) )
to
pow( xN - x , 2 )

dusktreader 137 Posting Whiz in Training

clock() returns the time in mili seconds,

Not so. This returns the number of clock ticks since the last call to clock(). What this number means varies by hardware and os.

CLOCKS_PER_SEC is the conversion
factor from the value returned by clock() into seconds.

That is so. so:
double secs = clock() / (double)CLOCKS_PER_SEC;
will give you the time in seconds since the last call to clock.

thanks.
i figured it out too.
im just confused by the innermost while since its my first time seeing a while without contents.

This is basically what you call busy waiting. The loop will essentially do nothing but check the loop condition. Once the loop condition is false, the program can move on. In general, busy waiting is not a desirable way to wait for a condition to resolve. The problem is that, for long intervals, this loop will waste a lot of processor cycles to no purpose. If you are concerned about correctness, you would need to calculate how much time remains until the condition resolves and then sleep for that interval. Sleep tells the OS that the processor can be used for other computations until a certain time interval has passed. Unfortunately, sleep() and usleep() are not c++ standards, so you would have to choose a platform dependant method of non-busy waiting. For simple experimental cases, however, busy waiting will be fine. Just be sure that you don't give it too long of a waiting …

dusktreader 137 Posting Whiz in Training

I need help with an assignment. I have to modify the program below to determine the number that was entered the most times in a row and display the output. I can not use files or arrays. I am having trouble with the logic and need some guidance. Thanks.

I would use 2 number groups. 1 would remember the max count and corresponding number, and 1 would remember the current count and number. Here's some qseudo code for this algorithm

def  doStuff():
    get input store in maxNum
    set maxCount = 1
    set currCount = 1
    set prevNum = maxNum
    while still getting input:
        get input, store in currNum
        if currNum == prevNum:
            currCount += 1
            if currCount > maxCount:
                maxCount = currCount
                maxNum = currNum
        else:
             currCount = 0
        prevNum = currNum
    return maxCount, maxNum
dusktreader 137 Posting Whiz in Training

this is the code ..but it is not displaying the first and the last number that came from the user.
anyone can help me with this small problem??

1. Use an index variable in your loops
2. You don't need to iterate over all of the values, testing each for even or oddness. Instead, step your loops by 2!

for( int i=evenStart; i<=seriesEnd; i+=2 )
        // do whatever.  The value of i will be even
    for( int i=oddStart; i<=seriesEnd; i+=2 )
        // do whatever.  The value of i will be odd

The trick here is setting evenStart and oddStart to the correct value based on a variable like seriesBegin

dusktreader 137 Posting Whiz in Training

so how can I make this accept all object types ?

create_object(object_type)
{
    new object_type myobject;
    _objects_.push_back(myobject);
    return _objects_.at(_objects_.end);
}

As long as your vector will contain homogenous types (i.e. they are all the same). You could use a templated function:

template<class T>
T& create_object( vector<T> objects ){
   T obj;
   objects.push_back( obj );
   return objects.back();
}

Please note that there is no good method for creating a container class to hold heterogenous data in c++. If you were brave, you could create a vector of void pointers, but you would have no way of knowing the type each element.

If you all of the items you need to put in the container are user defined types, then you could have each class inherit from some arbitrary base class, and then you could create a vector of pointers to the base type object:

class Derived1 :  public Base{....}
class Derived2 : public Base{...}
vector<Base*> v;
Derived1 a;
Derived2 b;
v.push_back(&a);
v.push_back(&b);