arkoenig 340 Practically a Master Poster

Use code tags. Without them, all your indentation goes away, which makes your code very hard to read.

If your book really contained the line

delete [] x,a,b,c,beta,gamma,r;

then I suggest you stop using that book, because the author doesn't know C++ very well. Ditto for the overall design of the program.

That said, the first place I'd look for your error is in the line

x(n-1)=gamma(n-1);

which surely should be

x[n-1]=gamma[n-1];

if that's not the only problem, please repost the code using code tags, and please tell us which line or lines the compiler said was in error.

arkoenig 340 Practically a Master Poster

And if i understand you correctly then this additional exit condition would serve as an alternative break point from the inner loop after my current check?

No, instead of your current check. Once 2 is in the prime vector, the next number to be tested is 3. 2 * 2 is 4, which is strictly greater than 3; so you won't run off the end of the vector even when you're testing 3. Once you've gotten 3 safely onto the prime vector, 5 and subsequent primes are a piece of cake.

So here's one way you might write it:

// This assert should succeed because we pushed 2 onto primes
assert (!primes.empty());

primeList_t::iterator iPrime = primes.begin();
while (*iPrime <= limit && (x % *iprime) != 0) {
    ++iPrime;

    // This assert should work because the square of the last element
    // of primes is strictly greater than x, so the test *iPrime <= limit
    // should ensure that iPrime never referred to the last element of primes
    assert (iPrime != primes.end());

}

if (*iPrime > limit)
    primes.push_back(x);
arkoenig 340 Practically a Master Poster

Since when is 4 prime? Isn't that what you're claiming in line 20 of your code?

Also, if you care about execution time, one easy way to speed things up is to observe that you don't have to divide a candidate by every prime; just by the ones that are <= the square root of the candidate.

You have to be a little bit careful about this to ensure you don't inadvertently treat a perfect square as a prime because of rounding error in the square root, but an easy way to do that is compute the square root, round it, and then increment the rounded square root until its square is greater than the candidate. In other words:

unsigned long limit = sqrt(x);
while (limit * limit < x)
    ++limit;

Now you know that limit is >= sqrt(x) even if there are rounding problems, and you can use iPrime<=limit as the ending condition for your inner loop.

arkoenig 340 Practically a Master Poster

It's probably better to read and write the entire object.
f.read( ( char* )aClassObject, sizeof( aClass ) );
f.write( ( char* )aClassObject, sizeof( aClass ) );

Don't even think about it. This technique will not work if the object in question contains any members of type string, or vector, or any other type that manages any auxiliary memory.

arkoenig 340 Practically a Master Poster

How about getting your program to compile and execute, then posting the version you executed along with its output, and explaining what it's doing that you don't understand?

If you have never written a C++ program that has actually compiled successfully, then you shouldn't be trying to write one this big for your first effort. If, on the other hand, you have written a program that has compiled successfully, then you should be capable of getting this one to compile too.

arkoenig 340 Practically a Master Poster

I am guessing from what you have posted that you have never successfully run a C++ program at all. I say this because of the large amount of stuff in your program that is simply not part of C++.

It is one thing to show someone a program and say "This program almost works, but there is a problem that I just can't find." It is something else entirely to post something that isn't a C++ program and say "Please make this work for me." If you had done the first of these, I'd be glad to help you, but I'm not willing to substitute for your textbook. Sorry.

arkoenig 340 Practically a Master Poster

Now you've set month to 11, which means that your arrays have only 11 elements; the last element of averageStore is averageStore[10], and so on.

The right way to do this is to set your upper bound (i.e. month) to the number of elements you want, so

const int month = 12;

and then to exclude equality from your loops, such as

for (int i = 0; i < month; ++i) { /* whatever */ }

Personally, I prefer to use != instead of <, because doing so lets me use the same style for forward iterators, which do not support <; but I realize that not everyone agrees with me.

By the way, I don't understand why you're evaluating some array elements and then throwing them asay, as you do on lines 124 and 133.

arkoenig 340 Practically a Master Poster

Did you call srand first?

MasterGberry commented: fast response +0
arkoenig 340 Practically a Master Poster

Change "int i = 0" to "vector<string>::size_type i = 0" in line 44 and to "string::size_type i = 0" in lines 58, 71, and 84.

Next time, please cite the text of the error message so we don't have to look it up.

Zvjezdan23 commented: Thanks a lot for your help +1
arkoenig 340 Practically a Master Poster

You first. Otherwise it looks too much like you're asking someone else to do your homework for you.

arkoenig 340 Practically a Master Poster

Here's my problem. The question you've asked looks like a homework assignment, which is intended to test your knowledge of pointers. If all you know about a pointer is that it is "a variable that stores a memory address," and you have a homework assignment that asks the questions that you've posted, it looks to me like there is some material in your textbook or classroom that you should have studied but haven't.

As a general rule, this list does not do people's homework for them. More specifically, if you've really told us all you know about pointers, then you do not know enough to answer these questions, so answering them would be helping you cheat.

Therefore, I would like to suggest that you spend some time studying what you are supposed to be learning about pointers, and try answering the questions again. If you have made a genuine try at it and still have trouble, someone here will be sure to help you. As it is, though, I think you're just hoping that someone else will do your work for you.

Moschops commented: Right on. +3
arkoenig 340 Practically a Master Poster

Wouldn't you think that when someone posts a program in a C++ forum and asks for help, the program would actually be a C++ program?

Fbody commented: You're tight, it does look more like Java doesn't it... +5
arkoenig 340 Practically a Master Poster

Sounds like you need to measure the time more accurately. I suggest wrapping another loop around the entire program to run it a thousand times or so, and figuring out from that how long it takes to run once.

arkoenig 340 Practically a Master Poster

Exactly. You have to initialize a reference and you don't have anything to which to initialize.

You are completely correct that a reference cannot be a member of a class unless every constructor initializes it. Part of the point of references is that they are always initialized.

If you want something that is similar to a reference but does not need to be initialized, you should use a pointer.

arkoenig 340 Practically a Master Poster

Here's a hint: You don't need an array.

arkoenig 340 Practically a Master Poster

The paragraph you cite is an example of explaining how to avoid a bad programming technique by using a second bad programming technique. Here's why I say that.

A reference is an alternative name for an object. For example, if I write

int i;
int& j = i;

then I am saying, in effect, that j is an alternative name for i; in other words, that i and j are two different ways of referring to the same object.

When you write a function that returns a reference, that function is returning an alternative name for an object somewhere, because that is what a reference is. For such a function to be meaningful, it must return a reference to an object that will continue to exist after the function has returned.

So, for example, if I write the following:

int& foo()
{
    int n;
    return n;    // Don't do this!!
}

I have written a function that behaves in an undefined way when I call it. The reason is that if I write

int& x = foo();

I am saying that I want x to be an alternative name for whatever foo returns. However, what foo returns is an alternative name to its local variable n, and that variable ceases to exist when foo returns. Therefore, it returns an alternative name for something that does not exist, and x is similarly caused to name a nonexistent object.

The bad programming technique here is …

arkoenig 340 Practically a Master Poster

It's your course.

arkoenig 340 Practically a Master Poster

Maybe your compiler doesn't completely support C++0x initializations yet.

What happens if you replace the curly braces with parentheses in the last line of code in your example, and change "auto" to "AoE2Wide::Item*" ?

arkoenig 340 Practically a Master Poster

First off, absolute brute force isn't going to work in this case as the input is in floating point, and you can easily get a function that has maxima at non-integer values.

The original problem statement constrains the arguments to integer values.

StuXYZ commented: Well spotted! +4
arkoenig 340 Practically a Master Poster

The code is indented properly. Perhaps you could get to the root of the problem instead and mention that mixing tabs and spaces can affect indentation when pasted outside of an IDE.

Aha! Frankly, the thought had not occurred to me that the website (or, perhaps, the combination of the website and my browser) would display mixed-tabs-and-spaces code so confusingly.

Looking at the code again, I am guessing that it was written in an IDE that assumes 4-character tabs, and displayed by an engine that assumes 8-character tabs.

I stand by my remark about trivially redundant comments.

arkoenig 340 Practically a Master Poster

In my earlier remarks I made a number of suggestions, including:

1) Most of your comments are so obvious that they add nothing to the code.

2) Learn how to indent C++ code.

As far as I can tell, you have ignored these remarks. Why should I look for new problems if you haven't done anything about the ones I already found?

arkoenig 340 Practically a Master Poster

Memory-mapped IO is not part of standard C++, which means that your instructor must be expecting you to use some locally defined facilities for the purpose. Your first job is to find out what those facilities are.

While you're doing that, I have three other suggestions:

1) Most of your comments are so obvious that they add nothing to the code. For example:

// If statement to check if i > j
if (i>j)

// Show that y is true
y=true;

// Return y
return y;

These comments make your program bigger, and therefore increase the amount of time it takes to read it; but they do not make the program any easier to understand.

2) Learn how to indent C++ code. Line 73, which is the beginning of an if statement, is indented less than line 76, which is the rest of that if statement. You should never write code like that.

3) Don't define useless variables. For example, your variables y and palin are each used in only a single place: You assign a value to the variable, use it once, and then never use it again. So, for example, instead of writing

y=true;
return y;

you can simply write

return true;

and instead of writing

palin=isPalindrome(data);
if(palin) // ...

you can write

if (isPalindrome(data)) // ...

In both cases you can not only get rid of …

jonsca commented: Good advice +6
jimJohnson commented: Great helper +0
arkoenig 340 Practically a Master Poster

Yes.

More seriously, if you're running this program on a 32-bit machine, you're probably asking for much more memory than the system is capable of providing; and it would not be surprising to learn that an overflow is taking place as part of computing how much memory you need.

arkoenig 340 Practically a Master Poster

I don't know what to put in replace of getHPData.

It's your program. If you don't know what you want it to do, how can you expect anyone else to know?

arkoenig 340 Practically a Master Poster

You've been studying this subject for two years. Surely you must be able to do something.

So how about showing us how much of your program you've written successfully. Then you might get a hint as to what to do next.

arkoenig 340 Practically a Master Poster

Step 1. Understand the problem thoroughly.

Step 2. Realize that I was really serious about step 1, and go back and understand the problem even more thoroughly.

Step 3. Write the clearest, most straightforward program you can that solves the problem correctly.

Step 4. Measure your program's performance. If you're satisfied with the results of your measurements, you're done.

Step 5. Your measurements will tell you what part(s) of your program are spending the most time. Rewrite those parts to make them faster. The most effective rewriting strategy will often be to find a way to avoid computing the same result more than once, or to find a more efficient algorithm. Now go back to step 4.

My experience is that many programmers will omit one or more of these steps in an effort to get the job done more quickly. Most of the time, doing so will have the opposite effect from what you intended.

VernonDozier commented: Good advice. +11
arkoenig 340 Practically a Master Poster

Please post the code you have written so far, and explain what problems you having in getting it to work.

arkoenig 340 Practically a Master Poster

Switch-case statements will work fine.

However, if you think that the hard part of the problem is deciding what kind of statement to use to detect parentheses, then I think you do not understand the problem.

I also think that before you start worrying about parentheses, you write a program that can handle the first of the examples correctly. In other words, write a program that can accept "2 - 3 * 4 + 2" as its input and give -8 as its result.

astala27 commented: That's what I am talking about. Thank you +2
arkoenig 340 Practically a Master Poster

The first function is riddled with errors:

1) It is missing two right curly braces.

2) Its parameter is named h but the body of the function uses an otherwise undefined variable named head.

3) The loop goes through only one iteration.

4) The code compares the pointer named current with 0, rather than comparing the contents of the node with 0.

5) The parameter is a Node* rather than a const Node*, even though there is no need for the function to modify the contents of any node.

The second function shares errors (2) and (5) with the first function. In addition, there is a subtle algorithmic disadvantage to what I think is the approach you're trying to follow, which is to compute the length of each list and then compare the lengths. The trouble with this approach is that if one of the lists is much longer than the other -- say, one has 10 elements and the other has 1,000,000 elements, your program will march out to the ends of both lists even though it really needed only to determine that the longer list had only a single element.

One way to solve this problem is to have two pointers that you step together each time through a single loop. As soon as either of them reaches the end of the list, you have your answer; it depends only on which pointer got to the end first (or whether they …

arkoenig 340 Practically a Master Poster

In the last section of code you posted, you are referring to DetectedFaces[j]. If TrackingFaces has more elements than DetectedFaces, at some point j will be >= DetectedFaces.size(). When that happens, DetectedFaces[j] is an out-of-range subscript.

arkoenig 340 Practically a Master Poster

Yeah but the function is recursive and is supposed to call itself until eventually it returns something.

Yeah but you're doing it wrong.

Every call, including recursive calls, must have a matching return. If any of these calls causes the "if" test in line 9 to be true, the corresponding return causes undefined behavior. The entire program could potentially do anything at all after that.

I really don't want to debate this. The code is broken, and there is no point in looking for any other problems until this one is fixed.

arkoenig 340 Practically a Master Poster

On line 15, you define a variable named "word." Because that is a string variable, it is automatically initialized to an empty string--that is, a string with no characters in it.

I do not see any place in the code you posted where you give a different value to that variable, which means that it is always going to be an empty string.

In line 20, you execute the statement word[l]='_', which is legitimate only if word has at least "l" characters in it. But we have already established that word does not have any characters in it. Therefore, this statement will always fail.

arkoenig 340 Practically a Master Poster

Why not define a third parameter to your addMap function:

// I changed the return type to void because you don't use the return value
void addMap(strMap& mymap, string Fname, string Lname)
{   // where Fname and Lname are strings entered by the user
    // in main that hold someone first and last names respectively.
    mymap[Fname] = Lname;
}

And then you can add an element to the map m by calling addMap(m, Fname, Lname).

The question remains as to why you would be using char arrays instead of strings for Fname and Lname, but you didn't ask about that :-)

arkoenig 340 Practically a Master Poster

I could tell you that functional programming (FP) is a style of programming in which one never changes a value that has already been computed. Instead, one creates new values as needed. By implication, using FP in practice requires a good garbage collector in order to get rid of values that are no longer needed.

Here's a simple example in C:

int factorial (int n) {
    int result = 1;
    while (n > 1) {
        result *= n;
        --n;
    }
    return result;
}

This code does not use FP, because it has the side effect of modifying the variables named n and result each time through the loop.

It is possible to achieve the same effect in an FP style, even in C, as follows:

int factorial(int n) {
    if (n <= 1)
        return 1;
    return factorial(n-1) * n;
}

You will see that in this second example, no variable is ever changed after being given its initial value, so there are no side effects.

The foregoing explanation is grossly oversimplified, and I can think of no short way to explain why FP is important or useful, but this is a start.

As for your other questions:

There are several programming languages in widespread use that make FP easy (or sometimes even necessary). The three best known are probably Lisp (particularly its Scheme dialect), Haskell, and SML. There are substantial differences between the three languages, but it's not easy to explain those difference …

arkoenig 340 Practically a Master Poster

OK, here's a trick. The hard part, as you will see, is figuring out how to unify the comparisons--i.e., to make the comparisons the same for each loop. So let's start in that direction by changing the comparison to inequality comparisons:

if (flag)
    for (i = 0; i != 10; i++)
        {LARGE_BLOCK_OF_CODE (that visits an array in order)}
else
    for (i = 9; i != -1; i--)
        {LARGE_BLOCK_OF_CODE (that visits an array in REVERSE order)}

Now let's unify the increment/decrement statements:

if (flag)
    for (i = 0; i != 10; i += 1)
        {LARGE_BLOCK_OF_CODE (that visits an array in order)}
else
    for (i = 9; i != -1; i += -1)
        {LARGE_BLOCK_OF_CODE (that visits an array in REVERSE order)}

Now the form of our two for statements is identical except for the values of three constants. So we can unify them by making those constants into variables:

int start, end, direction;

if (flag) {
    start = 0;
    end = 10;
    direction = 1;
} else {
    start = 9;
    end = -1;
    direction = -1;
}

for (i = start; i != end; i += direction)
    {LARGE_BLOCK_OF_CODE (that visits an array in the specified order)}
jonsca commented: Good one +5
SoftwareGuy commented: Not only gave the answer, but explained it really well. Thank you! +1
arkoenig 340 Practically a Master Poster

Compared to swapping by using 3 variables, this is akin to MOV operations on the processor which are generally more expensive than XOR operations.

Really? Why do you think so?

An assignment requires one fetch and one store. An XOR requires two fetches, one store, and the XOR operation itself. So why do you think that three XOR operations would be faster than three assignments?

arkoenig 340 Practically a Master Poster

I'm sticking with my last suggestion:

Before you ask other people to spend time reading and discussing code you have written, that you first take the trouble to (1) explain what you expect the code to do and why you are writing it, and (2) verify that the code actually compiles and does what you claim it does.

arkoenig 340 Practically a Master Poster

The easiest way to improve it is to throw it out and use the queue implementation from the standard library. Why reinvent the wheel?

If your purpose in writing this code is as an exercise, rather than to do something that you intend to be useful, then I don't understand how you got this code to compile. Line 15 is not valid C++, and lines 34 and 41 make no sense. I can guess what you intended them to do, but they don't do that.

Despite your name of Queue, the code you have written appears to implement a stack, not a queue. I say "appears" because it's not hard to find errors in the code--though it would be easier if it were possible to compile the code in the first place.

I would like to suggest that before you ask other people to spend time reading and discussing code you have written, that you first take the trouble to (1) explain what you expect the code to do and why you are writing it, and (2) verify that the code actually compiles and does what you claim it does.

arkoenig 340 Practically a Master Poster

I don't think you read either of the last two messages in this thread. Because if you did, you would understand why the very first statement in your example:

char* nstring="C:\Program Files\C++\myfile.txt";

simply does not work.

The rest of your code does not work either. The statement

nstring << nstring + "\\";

is just plain nonsense. If you're writing code like this, it suggests that you don't understand anything about how C++ expressions work.

I don't mean to sound unkind, but I think you should spend some time studying a good C++ textbook before asking other people for advice. It is very inefficient to try to learn by asking questions about material you don't understand in the first place.

arkoenig 340 Practically a Master Poster

This is for my Data Structures class. This is all we were given:

I understand what your assignment is.

What I am asking you to do is to explain the program that you wrote.

You say that it is producing results that you do not expect.

I am asking you what results you expect the program to produce, and why you expect the program to produce those results. An answer to that question would be something like:

"Well, the first statement sets this variable to this value, and then the next statement prints that variable, so I would expect it to print the value of the variable" and so on.

jonsca commented: Yep +5
arkoenig 340 Practically a Master Poster

Your vector 'quantity' is uninitialized, which means you are trying to print garbage.

Not true. If you create a vector of integers and do not initislize it, the integers are initialized to 0.

More generally, if you create a vector of objects of type T, the initialization process creates an object initialized with the value T(), then copies that object into each element of the vector.

arkoenig 340 Practically a Master Poster

Two suggestions:

1) Learn how to use code tags; without them, your code is very hard to read.

2) Pick one function from the collection of functions described in your assignment and implement that. Post your implementation.

arkoenig 340 Practically a Master Poster

It definitely can be done in linear time, just because of its special nature, that is because of the properties, 1,2,3,4 listed above.

Indeed. I had figured that the reason that no one bothered to answer it was that it was so easy.

However, since no one has made any progress so far, I'll give a few hints:

1) The O(n) space requirement means that it is possible to make temporary copies of the arrays. Therefore, we can assume without loss of generality that it is OK for the algorithm to change the contents of the arrays.

2) The constraints on the values of the array elements means that it is possible to use a radix sort to sort them, which is O(n).

3) Once the arrays are sorted, there is a trivial O(n) algorithm to determine whether they are disjoint.

I'll leave the code to someone else.

arkoenig 340 Practically a Master Poster

If this is the biggest problem of your life, you are truly blessed.

Fbody commented: LOL! :) +4
arkoenig 340 Practically a Master Poster

The technique that jonsca describes is widely used, and I'll bet that most of the people who use it fail to realize that it doesn't quite work: The numbers yielded by rand()%n are not uniformly distributed unless n is an exact divisor of RAND_MAX+1.

I believe that if n is not a divisor of RAND_MAX+1, there is no way to solve the problem correctly without using a loop (or an equivalent recursive function call). With that understanding, here is a function (slightly modified from page 135 of Accelerated C++) that takes an argument n and returns a uniformly distributed random number that is >= 0 and < n:

int nrand(int n)
{
    assert (n >= 0 && n <= RAND_MAX);
    const int bucket_size = RAND_MAX / n;
    int r;

    do r = rand() / bucket_size;
    while (r >= n);

    return r;
}
arkoenig 340 Practically a Master Poster

Your a teacher? A professor?

I'm a coauthor of this book.

jonsca commented: The master is finally revealed! +5
arkoenig 340 Practically a Master Poster

In order to solve a problem successfully, you must first understand what it is.

One way to test your understanding is to solve a simple version of it by hand, without using a computer.

So... m = 13, n = 241. In other words, what is the base-13 representation of 241?
Your turn.

I'm going to guess that your answer will be "I don't know." If that's true, no code that anyone writes will help you, because the best you can hope for is a solution to a problem that you still don't understand, and from which you will therefore learn nothing.

arkoenig 340 Practically a Master Poster

I don't understand -- what aspect of the program's behavior are you proposing to change, and in what way?

arkoenig 340 Practically a Master Poster

I am sorry to say that this entire long message is based on a fundamental misconception.

The name of an array is not a pointer. Its type is an array type, not a pointer type. Array types and pointer types are different from each other.

You can see this difference in several contexts. For example:

int x[10];
std::cout << sizeof(x) << std::endl;

If x were a pointer, then sizeof(x) would be the size of a pointer; but if you try running this code, you will see that it isn't.

As another example, consider

int arr[5];
int *const *const p = &arr;

Again, if arr were a pointer, this code would compile, but it doesn't.

What is true is that if you use the name of an array in most contexts (the main exceptions being to bind a reference to it or to use it as an operand of unary & or sizeof), it is automatically converted to a pointer to its initial element.

arkoenig 340 Practically a Master Poster

I'm sorry if I've offended you, but this discussion group doesn't do other people's homework for them.