dusktreader 137 Posting Whiz in Training

For this task, you should really use Regular Expressions. There aren't any regular expression parsers built into standard c++, so you will need to install a library. Boost has a good one that I know of, but there are others.

Now, you might be saying, "screw that, regular expressions seem too hard!" However, believe me that when you are facing complicated data, you want to use a flexible, pattern-matching technique. Regular expressions are the best and easiest way to look for specific text patterns in a heap of crazy data.

If you were open to other languages, you might check out Python for this task. Python manages text files better and simpler (in my opinion), and it has built in regular expression functionality.

Another alternative is to use a Finite State Machine to match the expression yourself. You would build the FSM in code, and use it to parse input. This will not be easy, but it will also work well.

In any case, I would suggest that you don't re-invent the wheel. Find yourself a library that can parse the patterns and use it.

dusktreader 137 Posting Whiz in Training

Hi i'm writing this program where the user chooses whether to print out a square, a forward triangle, and a backwards triangle using the "*" character. I got the square and the backwards triangle to work and the forward triangle, but i cant figure out how to do the back wards one.
*
**
***
**** is how the foward triangle looks when the user enters the size of 4 the backwards one should look like

*
**
***
**** when the user enters 4 for the size. my code for the normal triangle is below(for some reason this wont show up how its suppose to but it should look the same as the normal triangle just slanting to the left instead of to the right.)

cout << "enter the size of your triangle." << endl;
cin >> size;

for(line = 1;line <= size; line++)
{
stars = line;
for(loop = 1;loop <= stars;loop++)
{
cout << "*";
}
cout << endl;
}

If anyone could help me to print out the backwards triangle with just if -else statements and loops that would be great.

The forward and backward triangles look the same to me. Perhaps you mean the backward one should look like this:
****
***
**
*

in any case, the code is simple. In the easiest version to code, you should have two loops. One will count down from your size to 1, one will count …

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
void operator= (monomial & p);
	monomial operator* ( monomial &p);
	monomial operator/ (monomial &p);
...
        monomial a1("a:b:c");
	monomial a2("a:c");
	monomial a8;
	a8=a1/a2
        a8.print();
	cout<<endl;

The problem, i believe, is that you are trying to pass a non const monomial reference to the assignment operator. This is fine if you are passing a reference to a variable like

monomial a1("a:b:c");
	monomial a2("a:c");
	monomial a8;
        a8 = a1;

However, the value you get back from the operator / hasn't been assigned to a variable yet. You can't change the value of this monomial, because it doesn't have a permanent address yet. These values are always const. Consequently, you need to change you assignment operator to take a const monomial for an argument. In general, you should use const protection wherever it makes sense

monomial& operator= ( const monomial & p){
         var = p.var;
         return *this;
}

The assignment operator should always return a reference to the monomial being assigned, so that assignments can be chained like a=b=c=d; This is done by having the code return *this. The argument should always be const, because while assigning p to this, you should never change the values in p

monomial operator/ ( const monomial &p) const;

This function creates a new monomial, sets its value, and then returns the new monomial. The values in p should never be changed, so we pass the argument as a const monomial reference. This will also allow the operator to operate on a monomial that …

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

Try this:

class NieDesktop : public Okno{
protected:
    Okno& ojciec;   
private:
    NieDesktop( Okno& _ojciec);
    NieDesktop(const NieDesktop&);  
};
NieDesktop::NieDesktop( Okno& _ojciec )
:ojciec(_ojciec){
}

OknoWlasciwe::OknoWlasciwe(Okno& _ojciec,int _x1,int _y1,int _x2,int _y2,string _nazwa) 
:NieDesktop(_ojciec){
    x1=_x1;
    y1=_y1;
    x2=_x2;
    y2=_y2;
    nazwa=_nazwa;
}

I haven't tested this with a compiler, but it is an idea. In this way you are calling the base class constructor first, which should set the reference, and then initialize the other values.

dusktreader 137 Posting Whiz in Training

I need to make a program that takes one character as an input and instantly continues execution and the time limit for the user to enter that character is 2 or 3 seconds. please help me and if possible ppost an example. Thanks for your help.

Please read this. There are plenty of people here who will help you solve problems with your code, but we do not want to do it for you. You have to try on your own first.

Try googling ctime for starters.

dusktreader 137 Posting Whiz in Training

Would you be so kind and help me solve this problem?
It doesn't compile. Compiler says that the line 23 causes problems and I don't know why. It says class OknoWlasciwe has no member called ojciec and how come?? I mean, OknoWlasciwe is a public subclass of NieDesktop, which has such a member, so I thought it had it too...

Tthe ojciec member of NieDesktop is private. This means that only an instance of NieDesktop can access it. If you want this variable to be visible to derived classes, you must declare it to be protected. If you want any member of a class to be visible to only itself, use private. If you want the member to be visible to itself and it's descendants, use protected. If you want it to be visible to anyone, use public.

Good luck!

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

thnx very much, you made some very good observations, and
indeed it works what you last posted, but you have some mistakes, maybe rush.

Yeah, sorry. Didn't notice I was trying to assign to the template type! Whoops.

but i wanted this

vector<T>::iterator it;

and this caused problems, then you said to handle it as an array and worked but is there a way to handle it with the way i first used?

Yes, you can use an iterator for any type in any stl container. Familiarize yourself with the information here: http://www.cplusplus.com/reference/stl/. This page is very helpful.

Also instead of returning the minimum value, consider returning the minimum index, that way the person calling the function also knows where the minimum is as well.

This would not be too difficult of a change:

template <class T>
T& vMin( vector<T>& v, int& m )
{
    m = 0;
    for( int i=1; i<(int)v.size(); i++ )
    {
        if( v[i] < v[m] )
            m = i;
    }
    return v[m];
}

I changed the function to return a reference to the minimum value. So, if you are using this function for large types, there is no copy in or out. The m variable refers to the index of the minimum value.

dusktreader 137 Posting Whiz in Training

post removed.....AncientDragon already said it

dusktreader 137 Posting Whiz in Training

Hello,
I am making some program, and have some problem, i want to list all files that are on HD, and if I want to list all files in C: with this command with only one backslash after C:( system(dir C:\ /s/b/a-d> C.txt)) it only list files that are in C:\Users\Tomo\Documents\Visual Studio 2008\Projects\name\name, but when I enter this command with two backslashs after C:(system(dir C:\\ /s/b/a-d> C.txt)) it lists all files in C:, what is OK, but there are many files that I want to read, and I cant add everytime one backslash more,(if I want to list all files in D:, I can do it with two or one backslash, no difference).
Note: I can list all files whith one backslash in CMD, but not in c++.
Hope you understand my problem.
Thans.

My guess ( I don't use Micro$oft! ) is that the double backslash is acting as an 'escape' character. This is what happens:
Most operating systems use special characters inside of strings to mean special things. For example '\n' means newline, '\t' means TAB, etc. So, whenever the program sees a \ it is expecting a special character to follow. This is called escaping, because the character that follows 'escapes' from being processed normally, and the computer tries to find the special command to execute for that character. In this case the "C:\ /s/b/a" is trying to escape a space and ignoring the \. Since there is no special command for …

dusktreader 137 Posting Whiz in Training

Glad I could help!

If you needed to keep track of all numbers entered the maximum # of times, you would just use some sort of container to hold all of the numbers that met the qualification. Then, if a new number exceeded the maximum, you would purge the container and insert only the new maximum.

Good work!

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

i don know about class n pointers,can u explain it with essy examples please

You should learn about google (perhaps you could google it? AAAHHH recursion! ). There are so many simple c++ tutorials and examples THAT ALREADY EXISTS AND ARE 1 GOOGLE SEARCH AWAY. Please try to solve your own problem before you ask for help.

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

Hi,
Could someone please let me know how to terminating char pointer array properly?

void constructSet (ptr s,int size)
{
	ptr ch;
	ptr first = s;
	int i;
	
	for (i = 0;i<=size;i++)
	{
		ch = new char;
		*ch =static_cast <char> ((rand()%26) + 65);
		
		if (checkSet (*ch , first , s)== false)
		{
			*s = *ch;
			++s;
		}
	}
	*s='\0';
}

This is probably where the problem you asked about is arising. You're going one step too far on your for loop.

Instead of :
for (i = 0;i<=size;i++)

try
for (i = 0;i<size;i++)


Also, follow the previous suggestions about fixing your memory management.

dusktreader 137 Posting Whiz in Training

Write a program for multiplication and division of two numbers for different base number.

Programme structure: The program should contain
1. Should have an infinite loop which is the program is always running.
2. An option for a user to select base number of the first number. (For example: base 2, base 8, base 10, base 16)
3. Then, again list the options of base number for the second number.
4. Then, do the multiplication and division of those two numbers.
5. Ask the user to choose the base number of the output.
6. Reminder: You have to check either the input from user is in the range of the base number. (For example: if the user enters number 4 in base 2. So, it is invalid since it is not in the base of 2)

This is obviously homework. If you don't even try the problems, how are you going to learn anything? When you cheat on homeowrk in classes, you're only cheating yourself out of knowledge.

Salem commented: Indeed, makes you wonder why some people ever bother to sign up for courses. +19
dusktreader 137 Posting Whiz in Training

You could also use the standard template library containers like vector, deque, list, etc. These are very handy, and vectors almost match arrays for performance. They are much harder to break (though still very possible), and can save you a lot of heart ache. If you want a simple solution, and a dynamically sized container, these are the way to go:

http://www.cplusplus.com/reference/stl/

Also, for my own two cents, I would drop MFC like a hot rock and learn up on WPF. To really keep up to speed on Windows programming, you should embrace the .NET framework. I would say, your old text still has a mountain of valuable knowledge, but you should supplement it with something up-to-date.

dusktreader 137 Posting Whiz in Training

Alright, well I figured out this solution while I was continuing working on it. Could someone brief over it and tell me if there's any memory issues?

double* loadfile (string path){
	double garray[96],temparray[192][79],firstaveragearray[96][79];
	...	
		double * address = & garray[0];
		return address; 
	
	else cout << "could not open file";
	
	return 0;
}

You are on a suicide mission with this code! However, it can be easily fixed. First, the the previous poster noted, you are allocating the array locally (to the loadfile function) and then returning a pointer to that locally allocated array. This is very, very bad. When you allocate a local array like
int localArr[10];
Inside of a function, the program reserves that memory space on the program stack. This memory is reserved only as long as the program is in that function. So, when you return a pointer to that memory, the pointer is invalid. Once the function has returned, the program can use the memory space that used to be restricted for local variabes for anything. The only reason you were getting back your values was because the program hadn't used that memory space yet, so the bits were unchanged. If you want to preserve data you need to use some sort of dynamic memory allocation like this:

double* someFunction(){
   double* someArray = new double[5];
   someArray[4] = 7;
   return someArray;
}
int main(){
   double *someArray = someFunction();
   cout << someArray[4] << endl;
   delete [] someArray;
   return 0;
}

Here, the new and delete

dusktreader 137 Posting Whiz in Training

Since you are using an array to emulate a dynamically sized container, I would definitely suggest you use a string type or container type from the standard template library. This way, you can be sure that you won't overrun your array, and you don't have to allocate large storage and re-allocate when you run out

#include <deque>
using namespace std;
int main(){
    deque<char> container;
    int n = 1000000;
    for( int i=0; i<n; i++ )
        container.push_front( ( rand() % ( 'z' - 'a' ) ) + 'a' );
}

This will stuff one million random characters into the dynamically sizing deque. You could use the simpler vector or string types, but they only support push_back(), so you would have to reverse the container before you could print its contents. If you are really going to use c++ to its full potential, you should definitely check out the standard template library. There are a bunch of goodies in there that can save you all kinds of time and seg faults!

dusktreader 137 Posting Whiz in Training

Containers can have as much memory as your computer has available. Each int requires four bytes of memory, minimum, whereas each char typically takes 1 byte of memory. Therefore, typically, it takes 4 times as much memory to store an int as it does to store a char. Each compiler is free to require more memory than the minimum established in the language standard, so the exact memory profile may be different with different compilers. In general, though, you can store more char than int in any given memory block.

This is true. If you think you might run out of memory, use chars instead. You should also note that chars can be signed just like an integer because they are actually an integer type with less bit depth! If you treat the chars exactly like you would an integer, all of the arithmetic will work the same so, for example:

char a = 7;
   char b = -9;
   char c = a + b;
   cout << c << endl;    // Weird output
   cout << (int)c << endl;   // Expected output

Try this out, and you'll see it works. When you printed c directly, it displayed some weird character, because printing a char uses the char's value to look up a symbol in the ascii table. We can be sure that looking up -2 in the ascii table is going to fetch a wierd symbol. However, since c instead holds an integer value, you simply cast it to an …

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

I wrote a class that functions correctly. However, I assume this is homework, so I won't give you the solution code. I will describe a good solution to the problem for you, though.

First, I don't really see a reason to use strings for your storage. You might use chars, but you would only be saving a little space over using ints. I used an int array. The trick here is your implementation of the addition operation. Here's some pseudo code for the solution method I used.:

1.  initialize temporary variables a, b, i, s, r, and sign
2.  Determine which operand is greater, call this operand A, the other B
3.  Set sign = sign(A) * sign(B)   #By sign, I mean +1 or -1
      Set r = 0  #r will be used for the carry/borrow
4.  Set i = 0 to start at the right-most digit ( the one's place)
5.  Set a = A[i],  b = B[i] iff i > length(B)  else b = 0  # If B has run out of digits, set b to 0
6.  Set s = a + b + r
7.  If this is the last digit of A
          If s is negative, put positive s into the ith place of the result
          Else if s is larger than 9, put s - 10 into the ith place and 1 into  i+1 place of the result
          else, just put i into the ith place
          Go to 10
8.  Else
          If …
dusktreader 137 Posting Whiz in Training

>On modulo: http://en.wikipedia.org/wiki/Modulo_...ormance_issues
Thank you for strengthening my case. Allow me to quote from the link that you apparently didn't read very carefully (emphasis mine):

Actually, I have read it carefully, and my most recent visit to that link was not the first. You'll notice that I didn't contradict your reply.

In other words, this is a pretty common optimization (which I can independently confirm). Not only would it be redundant to optimize an expression that the compiler will optimize for you, it's entirely possible that you could end up confusing the optimizer and getting worse results than straightforward code.

It's not uncommon for cleverly "optimized" code to often end up slower than stupid code for that very reason. One good example is the XOR swap.

If you write a lot of cross platform code (which I do), you can't really make assumptions about the compiler that will be used to build the application for end users. It is not bad practice to use explicit optimizations rather than relying on the compiler to do it. If the optimizations are simple and clean ( such as >> & ), you can be fairly confident that the compiler won't get confused.

But don't forget that performance is relative. If % is "much slower" than &, but they both occur so fast nobody gives a rat's ass, why bother squeezing out extra performance that won't be noticed? It's wasted effort and diminishes code maintainability.

That's quite an assumption. …

dusktreader 137 Posting Whiz in Training

Thanks dusktreader for answering :)
Actually, I looked at your code while reading the line "it keeps the code from executing a switch on every single iteration of the loop" and therefore got confused.

The switch statement is really just a convenience wrapper for a regular conditional (if). A for loop already has a conditional that is executed in every iteration. Usually this is a check to ensure that the index hasn't exceeded the limit of the loop: for( int i=0; i<n; i++ ){...} If you can help it, you don't want there to be another conditional inside of the for loop, otherwise, the program has to check it on every iteration.
So, this:

for( ){
  if( C == A )
      someOperation();
  if( C == B )
      someOtherOperation();
}

Has to check the value of C on every iteration of the loop. Though it doesn't look as clean, it would be more efficient to write:

if( C == A )
    for()
        someOperation();
if( C == B )
    for()
        someOtherOperation();

This way, the test on the value of C is only performed once. This is a small optimization, but in a large project, simple boosts can gain a lot!

Mat[][] is a private member of class Matrix object other, can it be directly accessed? I don't think so.

Actually, it can directly access the private members of another class of the same type. Try this code out:

#include <iostream>
using namespace std;
class Dummy{
private: …
dusktreader 137 Posting Whiz in Training

What's the compiler error look like?

dusktreader 137 Posting Whiz in Training

So I'm working on this class, which is basically to wrap a char into 8bools, and it works so far, however I'm running into a problem, in the dedication of values, since I'm to use the overloaded array operator, as well as the overloaded assignment operator, at once, however I can't really find the way to do this; this is my code:

Main.cpp

...
    CharBool = alfa; // Missing the possiblility to do CharBool[Number] = bool
                     // and the ability to do; CharBool[Number] = true (or false for that matter).

Boolean.cpp

...
bool Boolean::operator[] (char nIndex)
{
if (nIndex>7){/*SENT ERROR MESSEGE*/return 0;}
return ((*Bool >> nIndex) & 1);
}
...

I don't think you'll have much luck getting b=true to work very well. You need to understand what is happening under the hood first. When you call operator[], you should be getting back a reference to some value. There are no values available that are smaller than a sigle byte. A character is a sigle byte. Therefore, you can't possible fetch a reference to the ith bit in a character. The best you could do is get a reference to the whole character. You can't literally assign a value to a single bit. Instead, you have to play tricks like using the bitwise or operator with an l-shfted 1 to set the bit. You could possibly hack this in a certain way. Include some private variable that would keep the index of the last requested bit, then, in the assignment operator, …

dusktreader 137 Posting Whiz in Training

I suggest this change.

sum += x;
		if (count==0){
		    largestnumber = x;
                    smallestnumber = x;
		}
                else{
                    largestnumber = max( x, largestnumber );
                    smallestnumber = min( x, smallestnumber );
                }

1. Use the += operator. It's just nice.
2 . You should you an if else statement. There's no reason to compare x to largest and smallest if count == 0.
3. I like to use the M = max( x, M ) synatax. It looks much cleaner and reads very easily.

dusktreader 137 Posting Whiz in Training

Are you macro protecting your header files?

#ifndef _SOME_HEADER
#define _SOME_HEADER
class SomeClass{...};
#endif

or

#pragma once
class SomeClass{...};
dusktreader 137 Posting Whiz in Training

yes, i know i should use cvFitline();
but as i stated i'm not sure what this function does.
what does it returns? and how do i work with it?

The link he provided describes everything you need. Also, this is a c++ forum, not an OpenCV forum. OpenCV has a very active yahoo group if you need help. However, most of any questions you have about OpenCV functionality can be answered by their extensive online documentation: http://opencv.willowgarage.com/wiki/. I use OpenCV extensively, and I visit that site at least once a day.

dusktreader 137 Posting Whiz in Training

No need for two loops here:
Given an array (arr), the starint index (j), the ending index (k) and the number of elements in the array (n):

int sum =0;
for( int i=j; i<k; i++ )
    sum += arr[i];

You will need to ensure that i >= 0 and k <= n

[edit]

I noticed that you use the terminating condition i < n-k. Just substitute this into the termination criteria (middle statement) in the for loop

dusktreader 137 Posting Whiz in Training

>bool isOdd = result & 1;
I wouldn't necessarily recommend it unless you can prove that the remainder operator is noticeably slow and bitwise AND is significantly faster. Decreasing readability for dubious performance gains smacks of bad practice.

On modulo: http://en.wikipedia.org/wiki/Modulo_operation#Performance_issues

Without compiler operations, modulo is much slower than bit-wise AND. However, as noted on the above link, most compilers will optimize the difference away. As far as pad practice, isn't optimizing C an irreconcilable trade-off between readability and performance? ;)

dusktreader 137 Posting Whiz in Training

I just used an explicit dot product function. Not as satisfying aesthetically, but functional. Thanks for the help.

dusktreader 137 Posting Whiz in Training

If I read this correctly, you are wanting to choose (with replacement) r items (points in this case) from a set of n items? This can be done easily using a vector to hold the sets:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(int argc, char *argv[]){
    int n = 13, r = 7;
    cout <<  n << "C" << r << " of integer set 0 to 12:" << endl;
    vector<int> inputset, outputset;
    for( int i=0; i<n; i++ )
        inputset.push_back(i);
    cout << "input set: ";
    for( int i=0; i<(int)inputset.size(); i++ )
        cout << inputset[i] << " ";
    cout << endl;
    for( int i=0; i<r; i++ )
        outputset.push_back( inputset[rand()%n] )
    cout << "output set: ";
    for( int i=0; i<(int)outputset.size(); i++ )
        cout << outputset[i] << " ";
    cout << endl;
    return 0;
}

Doing nPr (randomly pick without replacement) is not much harder:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(int argc, char *argv[]){
    int n = 13, r = 7;
    cout <<  n << "C" << r << " of integer set 0 to 12:" << endl;
    vector<int> inputset, outputset;
    for( int i=0; i<n; i++ )
        inputset.push_back(i);
    cout << "input set: ";
    for( int i=0; i<(int)inputset.size(); i++ )
        cout << inputset[i] << " ";
    cout << endl;
    random_shuffle( inputset.begin(), inputset.end() );
    outputset = vector<int>( inputset.begin(), inputset.begin() + r );
    cout << "output set: ";
    for( int i=0; i<r; i++ )
        cout << outputset[i] << " ";
    cout << endl;
    return 0; …
dusktreader 137 Posting Whiz in Training

Any other comments or suggestions? :)

Line 24 (and others): Watch out for shadowing class members with function arguments. There is a function called init, so you should probably make this argument initVal. This is more readable anywya.

Line 34 (and others): Inside of the scope of the Matrix class, you have access to the mat array member. So, you should use direct access instead of accessor functions within this scope. So use mat[j] = other.mat[j]. This is also more readable, and it is more obvious what is going on.

Line 45 (and others): Move this conditional above the switch. There is no use repeating the same code in all the branches.

Line 49 (and others): Move the initialization above the switch. No use repeating.

Line 53 (and others): Move the return statement below the switch. No use repeating.

Line 69: Why is the conditional for the MLT case different? For a per-element multiplication, the constraints should be the same as the other operations. Also, just use other.row since it is within scope. Cohesion and consistency are as important as readability.

Line 134: I'm surprised your compiler signed off on this. The setw function isn't templated ( on my compiler ), so I couldn't include this. Also, would the setw know what to do if the X was a user defined type. If you had a type that was overloaded for +, -, *, and << you could create a Matrix of this type. …

dusktreader 137 Posting Whiz in Training

@dusktreader - Thanks for the code, I'll take hints from that. I thought of using single dimensional array for representing the matrix but then change to two dimensional to support user's view of the matrix.

notice that I overloaded the () operator to allow access to an item by (row, col), so Mat( i, j ) will return the item at the ith row, jth column. You can easily expose 2d functionality ( or higher D if you are careful and clever ) to a user while preserving the underlying 1D structure.

Also, I didn't got what you meant by this "but it keeps the code from executing a switch on every single iteration of the loop" :-/

@first person suggested a helper function that looked like this:

void _arithmeticHelper(const Matrix& other, const int& Operator){
 for i = 0 to Row
   for j = 0 to Col
    switch( Operator){
     case ADD : _myMatrix[i][j] + other._myMatrix[i][j]; break;
     case SUBTRACT : ... break;
     case MULTIPLY : ... break;
    }
}

Notice that in this code, the switch statement is inside of the nested for loop. This means that the program will be required to branch ( execute an if statement ) in every single iteration of the loop.

I suggest this as an alternative:

Matrix arithmeticOperator( const Matrix& other, ops op ) const{
    if( mat == NULL || other.mat == NULL || other.rows != rows || other.cols != cols )
        return Matrix();
    Matrix neo( rows, cols );
    switch( …
dusktreader 137 Posting Whiz in Training

Hello! I'm beginning learning C++ and I was wondering, does Visual Studio 6.0 support all of the language features or is it too outdated now? If so are there any free compilers/linkers that I can use for windows programming? I'm also worried about the windows API headers being outdated as I plan to get windows 7 soon.

Also, I noticed that the windows controls in VS6.0, like buttons and textboxes, don't even have the XP style and they look more like windows 98 style. Why is that and can I change it somehow?

TIA!

Qt Creator is a great integrated IDE for c++ development within the Qt framework. Qt is very portable cross platform GUI toolkit. If you are looking for a free IDE / GUI creator you should really check it out:
http://qt.nokia.com/products/developer-tools

dusktreader 137 Posting Whiz in Training

Here is a working example with a few notes at the bottom:

#include <iostream>

using namespace std;

enum ops{ ADD, SUB, MLT };

template <class T>
class Matrix{
private:
    T* mat;
    int rows;
    int cols;
    int sz;

    void initMat( int rows, int cols ){
        if( rows <= 0 || cols <= 0 ){
            mat = NULL;
            return;
        }
        this->rows = rows;
        this->cols = cols;
        sz = rows * cols;
        mat = new T[sz];
    }


public:
    Matrix(){
        mat = NULL;
    }

    Matrix( int rows, int cols ){
        initMat( rows, cols );
    }

    Matrix( int rows, int cols, T initVal ){
        initMat( rows, cols );
        for( int i=0; i<sz; i++ )
            mat[i] = initVal;
    }

    Matrix( const Matrix& other ){
        initMat( other.rows, other.cols );
        memcpy( mat, other.mat, sz * sizeof(T) );
    }

    ~Matrix(){
        delete [] mat;
    }

    T& operator()( int row, int col ) const{
        return mat[ cols * row + col ];
    }

    Matrix operator+( const Matrix& other ) const{
        return arithmeticOperator( other, ADD );
    }

    Matrix operator-( const Matrix& other ) const{
        return arithmeticOperator( other, SUB );
    }

    Matrix operator*( const Matrix& other ) const{
        return arithmeticOperator( other, MLT );
    }

    Matrix arithmeticOperator( const Matrix& other, ops op ) const{
        if( mat == NULL || other.mat == NULL || other.rows != rows || other.cols != cols )
            return Matrix();
        Matrix neo( rows, cols );
        switch( op ){
            case ADD: for( int i=0; i<sz; i++ ) neo.mat[i] =  mat[i] + other.mat[i]; break;
            case SUB: for( int i=0; i<sz; i++ ) …
vidit_X commented: Thanks. +2
dusktreader 137 Posting Whiz in Training

y=f/2; //This will tell you nothing about the evenness of f
if ( y= 0) //This will always resolve to false because the assignment operator essentially returns the rvalue, which is always 0 in this case. Perhaps you meant y==0 ?
cout<<"even";
else
cout<<" odd";
}

This is a good way to avoid the costly mod operator (if this was your intention) while determining if a number is even:

bool isOdd =  result & 1;

This works because all even values have a 0 in the least significant bit, while odds have a 1 in the LSB. The bitwise operator will essentially test the LSB, and return 1 if the LSB is 1, and 0 otherwise. You can see this for yourself with this code

#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
    for( int i=0; i<14; i++ )
        cout << i << " is " << ( i & 1 ? "odd\n" : "even\n" );
    return 0;
}

This could be easily applied to this problem by using this line

cout << "your result is " << ( result & 1 ? "odd\n" : "even\n" );
dusktreader 137 Posting Whiz in Training

Just curious, are you creating a 2d and 3d vector class.

Yes, they are 3d vector classes that I am using in a custom built raytracer. I implemented it in Python last year, now I'm moving it over to c++.

dusktreader 137 Posting Whiz in Training

I was afraid of that. Downcasting pretty much ruins the aethetic elegance of operator overloading in this case. I think I'll just use a

double Derived::dotProd( Derived& other );
dusktreader 137 Posting Whiz in Training

Let me spell it out to you :

main.cpp: In function ‘int main(int, char**)’:
Inside your main function
main.cpp:15: error: no match for ‘operator*’ in ‘d * 1.0e+0’

There is no matching function function in the call :"e = d * 1.0;"

derived.h:15: note: candidates are: double Derived::operator*(const Derived&) const

It even says it here, the only valid function is "double Derived::operator*(const Derived&) const"

Please don't talk down to me. I am quite capable of reading a compiler error verbatim. However, I am not sure why the declaration of the dot product operator (Derived::operator*) is seeming to collide with the scalar product operator (Base::operator*). Neither have the same return type or parameter signature, so it seems that there should be no collision. I would really like to use the * operator in the Base class ( a generic triple scaling operation ) for all derived classes ( such as Vectors, Points, and Colors ) and overload the * operator for each as is suitable. For example, a dot product of two Vectors is a reasonable operation, but a dot product of two Colors makes no sense. Can there be only one operator overload for a given class heirarchy?

dusktreader 137 Posting Whiz in Training

bump.

Please help, I can't seem to find a good explanation of why this is happening, and it's keeping me 2 steps away from actually my application. This is a dummy example that is a simplified version of what is going wrong with my greater application. The thing about this that bothers me most is that when I remove the

double Derived::operator*( const Derived& other ) const;

function from the derived class, the scalar multiply works fine. Please help, thanks.