Bench 212 Posting Pro

There's a bit of a nasty trick you can perform with arrays and references which can mimic the effect of modifying different data members of a class/struct at runtime.

Given a simple struct like the following

struct person
{
    std::string forename;
    std::string surname;
    std::string telephone;
    std::string postcode;
};

Here, there's no safe nor portable way to maintain the names in the struct as well as being able to switch between them at compile time

One possible way around this is to stick all the data members in an array

struct person
{
    std::string vars[4];
};

but that loses the nice, comfortable member names which are important for readability.

A common solution in C is to use an enum to index different members in a struct, but this is hardly elegant

struct person
{
    std::string vars[4];
}; 

enum { forename , surname , telephone , postcode }; 

void func()
{
    person my_person;
    my_person.vars[forename] = "John";
}

A cleaner solution is to assign references to each position in the array. which makes the existence of the array all but invisible, except for those situations when you need to switch between data members at runtime

struct person
{
    std::string vars[4];
    std::string& forename;
    std::string& surname;
    std::string& telephone;
    std::string& postcode;

    person() : forename(vars[0]) ,
               surname(vars[1]) ,
               telephone(vars[2]) ,
               postcode(vars[3])
    {}
};

I'd still question as to exactly why you feel need to switch between data members at runtime, but references are a cleaner solution than macros at least.

Bench 212 Posting Pro

There's plenty of ways around the many problems associated with cin >> ; IMHO the best way to avoid them is to never use the >> operator in conjunction with cin in the first place (unless its really necessary).

My personal preference is to keep a separate function which grabs a line using getline(), and a stringstream to convert your input to whatever numeric type you need.

bool read_float( std::istream& in , float& num )
{
    std::string str;
    std::getline( in, str );
    std::istringstream iss( str );
    iss >> num;
    return iss.good();
}

This has the added bonus of removing the risk that cin will fail due to invalid chars being typed. You can check for this after asking the user to enter the price of the pie.

cout << "\nEnter price of pie:";
while ( ! read_float( std::cin , g ) ) 
    std::cout << "Invalid input - Enter price of pie: ";

One slight nitpick - the default floating-point type in C++ is double. For that reason its usually recommended to always use double whenever you need floating point numbers, unless you have some compelling reason otherwise to use float (which generally suffers from low precision. usually only 5 or 6 s.f. on most modern machines)


edit if you want to be extra-clever you can template the 'read' function to work with other numeric types (which would be handy if you wanted to do the same with int or double)

template <typename Ty>
bool …
Bench 212 Posting Pro

You're presumably trying to call your function called search() but you also have a local variable called search too. The compiler doesn't understand, and thinks you're referring to that variable. I'd suggest you call your variable something else instead

Bench 212 Posting Pro

Hi ,

Sorry for the trouble , i realised that dynarray is a memeber of namespace std.

I replaced it with Darray and the code compiled clean .

Thanks

No it isn't, the compile error was a simple typing mistake.

Bench 212 Posting Pro

Look very closely at this line dynarray(const [b]dynarrray[/b] &ob); I believe you probably meant to type dynarray instead

Bench 212 Posting Pro

Noone will spoonfeed you any solutions. have a good attempt at the problem for yourself and come back if you get stuck on anything along with a description of whatever it is you need help with, and the code you've tried so far.

Bench 212 Posting Pro

It sounds as if you need to set up some accessor/modifier methods within your account class, rather than attempting to access them directly from your bank member functions. private data members of a class can only be directly accessed from other members of that same class

Bench 212 Posting Pro

Presumably you're already passing the array in as a parameter, so returning it is a little pointless (The original will be modified anyway, since arrays are always passed by-pointer to a function).

Arrays aren't copyable, so they must be returned by-pointer. The syntax gets a bit messy, so you ought to use a typedef to simplify things a little

const int num_elems = 10;

typedef int (*array2d)[num_elems];

array2d function (int arr[][num_elems])
{
    return arr;
}

Without the typedef you'd end up with brackets all over the place, like this

int (*func (int arr[][num_elems]) ) [num_elems]
{
    return arr;
}

Just a word of warning - if you do insist on returning arrays from a function, make sure that the array has been declared outside of the function from which its returning, otherwise the end of the function will cause the array to be destroyed, and your program will most likely crash or display some other kind of undefined behaviour.

//Very bad! - Do not ever do this!
int (*function () ) [num_elems]
{
    int my_array[5][num_elems];
    return my_array;
}
Bench 212 Posting Pro

A pointer is an object which represents an address in memory.
A reference is just a 'nickname' or 'alias' for an existing object.

I'm not going to go into any further detail since the nature of the question sounds a little bit like 'please do my homework for me'. Have you tried a google search? you ought to be able to come up with some fairly detailed search results about Pointers-vs-references

Bench 212 Posting Pro

A few comments

- When handling dynamically allocated memory in C++, you should use the new operator. Malloc is bad, since all it does is allocate memory on the heap - if you're creating an object of a particular class/struct, then that object will be uninitialised.

- Keep in mind the rule of three, which states that if your class needs either a Copy Constructor, a Destructor, or an overloaded assignment operator, then it generally needs all 3.


In reply to Alex Edwards - What exactly do you intend the copy constructor in your example to do? at the moment the program displays undefined behaviour where you have a dangling pointer to an array which will be deallocated as soon as the object has been created. The result is neither a deep nor shallow copy of the original object, but just an object in an invalid state.


To the OP - perhaps you could explain exactly what it is you're trying to do here since void pointers are generally unsafe (You need to know exactly what you're doing in order for them to be meaningful); The initial example you provided is displaying that output because your object is being directly copied value-for-value (A shallow copy). Which means your array is copied as you'd expect, and the pointer member is also having its value copied.
If you posted the copy constructor which you tried, someone may be able to point out where …

Alex Edwards commented: Thanks for pointing that out! +3
Sulley's Boo commented: and happy belaaaaa..aated b-day :D +5
Bench 212 Posting Pro

I'd be willing to bet that the vast majority of C++ developers rarely touch the Windows API directly. Even if you limit that group to just those who even develop applications for Windows platforms, much of the time the Windows GUI code is likely to be wrapped up in several layers of libraries which support the basic structure of the application, or even written using another language altogether

Bench 212 Posting Pro

You mentioned that you attempted a return type of Tree<T>::Node , However, that's not sufficient for the compiler to take your word for it that Node is indeed a type identifier and not something else.

The issue is that Tree<T> is an incomplete type, where Tree::Node could be absolutely anything depending on the specialisation of Tree<T>

The solution is to use the typename keyword to give the compiler the extra hint that Tree<T>::Node is indeed a type

template<class T>
class Tree {
    struct Node { int a, b; };
    Node createNode();
    T b;
};


template<class T>
typename Tree<T>::Node Tree<T>::createNode() {
    std::cout<<"how are you\n";
    Node n; n.a=n.b=10;
    return n;
}
Bench 212 Posting Pro

Why don't you try it for yourself and find out? If the compiler doesn't complain, then you know its ok

The only point where your compiler might produce an error, is if you attempt to compile under C++, where true and false are reserved words which cannot be reused elsewhere. This shouldn't be an issue under C

Bench 212 Posting Pro

I'm not sure what language that is, but its not C or C++, unless the contents of "resource.h" happen to be an extremely nasty set of macros and #define statements.

If we knew what was inside resource.h. we might be able to give a better answer

Bench 212 Posting Pro

I bought the book C++ Primer Plus http://www.amazon.com/C%2B%2B-Primer-Plus-Stephen-Prata/dp/0672326973/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1202680271&sr=8-1 because i plan on learning the C++ language, but i can't really understand what it is trying to say when it is suggesting compilers. Can anyone give their feedback on the best compilers for beginners?

I assume you're after an IDE aswell, or do you intend to use a plain text editor (such as Notepad)? I also assume you're running Windows. If you're running linux, you're already equipped with the GNU Compiler Collection (GCC).

IDE's are a matter of personal taste. That being the case, you might want to try several of these, and decide which one you find easiest to use. (I would probably suggest Code::Blocks, because that one seems fairly beginner friendly)

Visual Studio Express: http://msdn.microsoft.com/vstudio/express/
Code::Blocks: http://www.codeblocks.org/
Quincy: http://www.codecutter.net/tools/quincy/
Dev-C++: http://www.bloodshed.net/devcpp.html
Turbo C++ Explorer: http://www.turboexplorer.com/cpp


If you just want a compiler which you can run from the command prompt, check out MinGW (which is a Windows GCC port)
http://www.mingw.org/

And also, C++ is the best place to start for a Game Programmer right?

That's fairly subjective, and depends what kind of games you want to write. C++ is used in alot of professional game development environments, where games are developed by large teams of people. Many large commercial games are written in C++, and some have released SDK's in C++.
- You could write …

Bench 212 Posting Pro

Assuming you're supposed to write your own, rather than use the standard C++ sort function, You'll need to implement a sort algorithm. a bubble sort or a selection sort should be fairly easy to write.

You'll find pseudocode for these here
http://en.wikipedia.org/wiki/Bubble_sort
http://en.wikipedia.org/wiki/Selection_sort

Bench 212 Posting Pro

it would appear that your plist is empty at the point where your debugger has reached that portion of code.

You might prefer to use the deque::at() function, which is bounds checked, and throws an out_of_range exception if you attempt to retrieve something from the deque which doesn't exist.

alternatively, you could check the element you're accessing against the size of plist

if( 0 < plist.size() )
{
    stl_index nodes_per_element = plist[0].size();
    deque<vector<stl_index> >::iterator it;
    //etc.
Bench 212 Posting Pro

In which case, the message may be telling you that you're attempting to de-reference the end() iterator (Which is actually 'one past the end'). To prevent the overflow problem, you might consider changing your loop terminating condition to eit2!=elmt_ids.end() If eit1 is always one step behind eit2, then this check ought to ensure both iterators stay within the boundaries of elmt_ids begin/end range.

edit - fixed BB code tag

Bench 212 Posting Pro

The only problem I can see with your code is that eit2 will overflow, being one step in front of eit1 each time. I can't see anything which looks like it should give a compiler error. Could you paste a more complete example of your code, since the actual problem may be elsewhere.

Bench 212 Posting Pro

The page appears to be over 10 years old, and the information probably older than that. Standard C++ does not have a class called ostrstream, and, to my knowledge, the standard C++ stringstream facility does not leak.

Bench 212 Posting Pro

The alternative, using the <map> library, if you'd prefer to give the orders a 'Key' value identifier

#include <map>

/* ... */

std::map< std::string, order > the_orders;
order my_order;
the_orders.insert( std::make_pair( "order1234", my_order) );

Although, the vector/deque solution posted by Salem is simpler IMHO.

A little more on maps -
http://www.cppreference.com/cppmap/index.html

Bench 212 Posting Pro

I think he asked for 250 miliseconds didn't he? not 25?

Anyway, it shouldn't matter, because there's no guarantee that CLOCKS_PER_SEC is equal to 1000 (I believe on POSIX systems its defined as 1000000)

I also think its a bad idea to use the name 'sleep' too, since its a common 3rd party library name in Windows and *nix, but that's just my opinion :) Although, if you already have the sleep function available, that's probably a better solution anyway (since its not tying up the system in a 'do nothing' loop )


a more portable solution might look like

void think( clock_t milliseconds )
{
    clock_t until = milliseconds * CLOCKS_PER_SEC / 1000;
    until += clock();
    while( clock() < until )
        ; /* do nothing */
}
Bench 212 Posting Pro

>main()
Why shoud i write when i do not need it ,when i need to write then i write.
>return 0;
Same thing .

main returns an int because the standard says it returns an int. if you omit the int return type from main then some compilers will complain and not compile at all, others might allow it to compile but your program will crash, other compilers might do something else.

You don't need return 0; at the end of main in C++ (though it might be good practice to do so), the C++ standard allows an implicit return 0 at the end of main.

Bench 212 Posting Pro

Huh? I assume DMA means Direct Memory Address. How does that relate to the discussion of this thread ? BTW DMA is not possible with any 32-bit compiler unless writing a kernel-mode device driver.

I think he means 'Dynamic Memory Allocation' - I could be wrong though. Either way, it works fine with both char and int

Bench 212 Posting Pro

If you were asked in another interview, which words would you remove from the English language, and why, how might you answer?

Then ask yourself what you think people who spoke the language would do after those words had been "removed" ?

Bench 212 Posting Pro

Additional:

It seems I was half-right, although, the STL uses the std::less<T> functor class as its default predicate for sorted containers, as found in the <functional> header. (std::less in turn assumes that operator< is available)

The STL also takes the extra step of enforcing the predicate to match a certain type (Which the example I gave doesn't do), using an additional template parameter, which defaults to std::less<T>. This is presumably a safety net to stop predicates for different types being used accidentally.

Bench 212 Posting Pro

I could be mistaken, though I believe that the STL sorted containers expect a type with a valid operator<. If the type doesn't provide one, then overloaded constructor(s) will take an additional parameter in the form of a compare function, or a function object which overloads operator() instead.

Since you don't know the precise type of the comparator in advance, you need to provide a templated constructor where any kind of comparator can be used to compare objects within the data structure


Here's a brief example of a constructor accepting a functor, whose type is determined at compile time.

/* less_comparator - user-defined comparison */
template <typename T>
struct less_comparator
{
    bool operator()(T, T) const;
};

template <typename T>
bool less_comparator<T>::operator() (T lhs, T rhs) const
{
    return lhs < rhs;
}

template<typename T>
class structure
{
public:
    structure() {}
    template<class Comparator>
    structure( Comparator comp )
    {
    }
};

int main()
{
    structure<int> s( less_comparator<int> );
}
Bench 212 Posting Pro

The best tip I can think of with regard to writing templated code, is to write a non-template version first. Then you can be sure that your program is correct for one type (such as int), and that you're happy with the design of your class(es). Afterwards, create a generic version of the code to work with any type, where, hopefully, the only problems you'll run into are simple syntax errors from the compiler.

Bench 212 Posting Pro

If you're able to split each 'word' into separate strings, then you're already half way there

use the toupper function on the first character of that word, to generate the uppercase equivalent of that character (If an uppercase equivalent is available).

word[0] = toupper( word[0] );

This won't solve the problem of converting all letters in acronyms to uppercase; eg, a string of "p.o. box" will only be converted to "P.o. Box", since there is no whitespace character between the 'p' and the 'o'.

- Depending on the exact requirements of your assignment, you may need to do some additional string parsing for characters which follow punctuation.

Bench 212 Posting Pro

The >> operator skips over whitespace automatically.

One alternative could be to capture each line of input from the file individually as a string, using the getline function.

std::string my_string;
while( std::getline( input, my_string ) )
{
    //TODO: Counting
}
Bench 212 Posting Pro

There's no such thing as a "Best" sorting algorithm. Depending on the amount of data you're holding, and how ordered the data is to start with, one algorithm may be better than the other in different situations.


If you wanted to test them out against each another, you could devise a way profiling them, eg, by measuring the time they each take to sort an array of a million randomly generated numbers, or by sorting some pre-defined sets of data and checking the number of passes.

The results are likely to be inconclusive, since there is no "best" sort algorithm. Have a look at this list of different sort methods - http://en.wikipedia.org/wiki/Sorting_algorithm

Bench 212 Posting Pro

It strikes me that your problem is confidence, and the best way to build confidence is to jump right in. Do something, anything, even if it turns out to be wrong. As it is you'll spend all of your time second guessing yourself and then you'll come to us at the last minute with the usual "my project is due in an hour and I haven't done anything!".

That appears to be almost every Computer Science student in the world these days - How fewer posts would this place get if students had 'more confidence'? ;)

Bench 212 Posting Pro

One thing I'd like to mention about the psuedocode comment - its unusual to specify data types in pseudocode - normally, details like that are left anonymous, concentrating on the high-level flow of the program

(The reason being that data types are an irrelevent detail from an algorithm point of view)

Bench 212 Posting Pro

at this line pizza.set ( x , y , a[7] , i ) ;

a[7] is an element in your array
(Also - if your array is only 7 elements in size, then valid elements are indexed 0-6, so you're accessing one-past-the-end.)

try this instead pizza.set ( x , y , a, i ) ;

Duki commented: thanks for the help +4
Dave Sinkula commented: Thanks. I had made that change but forgot to post it. +11
Bench 212 Posting Pro

That's the one that made me wonder if it was practical. All of the examples that look useful to me are too complicated to understand. All of the examples I can grok are kind of pointless. In the factorial one, you have to give the template a literal. If you know the literal you want, why not just use the factorial answer as a literal instead of some convoluted scheme of finding it at compile time with templates?

I just don't get it. :(

I understand your frustration.. there's still one or two pages in the book Modern C++ Design that frankly leave my head aching when I try to work out what the examples are actually doing

Yes, the factorial program on its own is rather pointless - it just shows how loops can be unrolled at compile time. Then again, most examples that you find in books are usually contrived, useless programs. I'm sure this can't be the first time you've looked at something in C++ and thought to yourself "Why on earth would I ever want to do this" :)


I think the advantage of template metaprogramming is two-fold. First, there's the minor goal of making your program more efficient, by performing certain routines at compile time. Although, if it were just about fine-tuned optimisation, then I expect most people wouldn't bother.

The more important goal (IMHO) is that doing these processes at compile time means more errors are picked up at …

Bench 212 Posting Pro

I appreciate your useful help and links, but I don't think I'm smart enough to understand template metaprogramming. Even the simple rebind you showed me before doesn't make any sense...

its a rather elaborate complicated example of template metaprogramming for a newbie IMHO. Try this as a simpler one :)

template<int N>
struct factorial
{
    enum { value = N * factorial<N-1>::value };
};

template<>
struct factorial<1>
{
    enum { value = 1 };
};

#include <iostream>
int main ()
{
    std::cout << factorial<6>::value << std::endl;
}
Bench 212 Posting Pro

Ah ok, sorry I misunderstood the original post - I thought you were after something that would allow reading the contents of the windows password files.

Bench 212 Posting Pro

AFAIK the C and C++ languages don't define the term 'handle', so its use can vary according to context.

In addition to the usage as described in Hamrick's link, some texts use 'handle' to describe C++ References .. in this context, 'handle' is a synonym for 'alias' or 'nickname'.

Bench 212 Posting Pro

That would probably be a password cracker's dream come true. Seriously, do you really think there's going to be an easy way to access encrypted Windows passwords like that?

(I am aware of programs which do this, but only by re-starting the computer and using a linux boot CD to bypass all the usual windows security stuff)

Bench 212 Posting Pro

anybody know how to see this???
(23,12,7) binary code???

Representing integers as a binary number..? if not, would you be a bit more specific?

Here's one way, using a bitset

#include <iostream>
#include <bitset>

int main()
{
    //bitset with 8 bits
    typedef std::bitset<8> bits_8;

    std::cout << bits_8(27) << '\n'
              << bits_8(12) << '\n'
              << bits_8(7)  << '\n'; 
}
Bench 212 Posting Pro

I haven't taken a math class in many, many years, but from what I can recall, you rotate a point by drawing a vector starting at the origin and passing through the point, and then rotate that vector 90 degrees, in this case.

Yes that's right, but it assumes you're rotating about the origin :) Either way, the origin is a point, so, as hamrick said, you need two points in order to rotate something. :)

Bench 212 Posting Pro
char studentgrade;
char lettergrade[1];
char A[1];

There's no point having an array of one character..

and there's no point storing seperate variables for each grade, you could just do this (note the single-quote marks)

if (studentgrade > 90)
	 {
	lettergrade = 'A';
	 }

You're on the right lines with the if (studentgrade > 90 ) stuff.

All you need is a few else-ifs for 80, 70, 60, etc.

Bench 212 Posting Pro

I think what you're seeing is a memory leak, the data isn't being deleted, its just being lost in the wilderness..

I assume that lst is the pointer to the head of your list (?), so don't modify that - the find_pos function is supposed to return a pointer to the element at position 'n'. Store the result in a temporary variable instead - something like this perhaps.

node* nth_node = find_pos(lst,n);
if( nth_node != NULL)
    lst = delete_node( nth_node, temp );
Bench 212 Posting Pro

Are you talking about C++ strings or C-style char arrays? (I assume you're talking about char arrays, based on your post)

What do you mean by "completely empty"?

You can make a C++ string blank by doing this

std::string name = "hello";
std::cout << name;

//Assign 'name' a blank string
name = ""; 
std::cout << name;

for a C-style char array, you could do this

char name[20] = "fred";
std::cout << name;

//If the first character is a null terminator, the string is 'empty'.
name[0] = '\0' ;
std::cout << name;

Or do you wish to iterate through every element and set each one to zero? (You can do that with a loop, although there's not much point.)

Allen Jay commented: this is the most helpful one +0
Bench 212 Posting Pro
case 2: di.getmeaning(word);//problem passing arguments

Here, you haven't asked the user to type in a word, so your string will be blank

Bench 212 Posting Pro

I see that the number is large enough but my mind still hasn't grasped how this number system works, is there some place I can read about it at my level to get my mind into how this works.
Thanks

That depends, this isn't really a programming question, but more of a discrete/pure mathematics one - How comfortable are you with numbers in bases other than 10? - particularly binary (Base 2), which is the only numbering system that the computer understands (All other numbering systems are representations of base 2)

If you've never touched binary arithmetic before, then spend some time going back to the beginning - how different number bases work, powers of two, counting in other bases, etc. There's a fair bit of background information to consider.

Bench 212 Posting Pro

Maybe i'm unclear of the question.. but a number is just a number - you can use it to represent whatever you want. There's nothing particulary special about your 32 bit max value.. some systems can handle more, other systems can handle less, although, if you get hold of a "big number" library for C++, there's theoretically no maximum number. (C++ unfortunately has no built-in support for numbers of unlimited size, and relies on 3rd party libraries - other programming languages do however)

Incidentally, in C++, you can find the largest and smallest numbers that a type can hold using a feature of the standard library called numeric_limits. If you use different types inbetween the < and > - you'll see that max/min values of types varies wildly.

#include <iostream>
#include <limits>

int main()
{
    int max = std::numeric_limits<int>::max();
    int min = std::numeric_limits<int>::min();

    std::cout << "Maximum value for an int is: " << max << std::endl;
    std::cout << "Mainimum value for an int is: " << min << std::endl;
}

Of course, systems do have hard limits somewhere. on a 32-bit platform, 4-billion(ish) is the maximum number of addressable memory locations, because address values are only 32 bits wide. Is this what you were referring to?


Also, I suggest you stay away from any book written by Herbert Schildt. Every review of his books i've ever seen suggests that he hasn't got a clue about the languages he attempts to teach - his books are …

SpS commented: Rightly Said About Herbert Schildt +4
Bench 212 Posting Pro

You'll need to explore a graphical API to create the GUI - this will depend what platform you're running

(Or you could explore a cross-platform API such as wxWidgets http://www.wxwidgets.org/ )

Bench 212 Posting Pro

Yes, it would be similar, except instead of looking for an element by checking its data, you'd be looking for an element based on its position. so you'll need a counter (A for-loop may be more appropriate)

I would probably do something like this

node* find_pos(node* list, int pos)
{
    for(int i=0; i<pos; ++i)
    {
        if( list == NULL )   //true if the list is shorter than 'pos'
            break;

        list = list->next;
    }
    return list;
}
Bench 212 Posting Pro

MingW is a popular windows compiler (for C and C++) - a windows port of the linux GCC tools.

have a look here http://www.mingw.org/

I have no idea whether it supports any of the GTK libraries you're using, you will most likely need to google around for windows versions of those