sepp2k 378 Practically a Master Poster

In a parameter list T arr[] is the same T* arr, so arr is a pointer. The only way to pass an array to a function is by reference. To declare an array reference you'd write T (&arr)[42] where 42 is the size of the array. In this case you'd probably want it to work with any size of array, so you'll need to make the size a template parameter like this:

template <typename T, size_t N>
void print_array(T (&arr)[N]) {
    ...
}

Now you don't even need to use the sizeof trick to get the length of the array, you can just use N.

The downside of this approach is that you'll only be able to use the method with variables of actual array types, so you won't be able to use it with arrays that have been allocated using new (as those would only be accessible through pointers - not directly through a variable). Of course that is true when using the sizeof trick as well.

If you want your function to be able to work with newed arrays too (or generally with arrays that you only have a pointer to), your only option is to take a pointer as your first argument and the size as the second.

sepp2k 378 Practically a Master Poster

To answer the question in the title: There's no way to find out the number of elements in an array if you don't know its type, but it's also not possible not to know the type of an array unless you only have a (void or otherwise casted) pointer to the array. And if you only have a pointer, you can't get the size anyway (regardless of whether or not you know the type).

It's not possible to get the size of an object from its type's typeinfo object.

heres the array:
int b[5]={20, 30, 40, 2};
length=sizeof(arr) / sizeof(arr[0]);

What's arr? You only showed us the definition of b.

why i don't get 5, but 1?

Presumably because arr is just a pointer, not an array, but we'd have to see the definition of arr to know for sure.

@UFOOOOOOOOOOO: That doesn't help you get the number of elements in an array though, which is what the OP wanted.

sepp2k 378 Practically a Master Poster
3(1-x3)

This is interpreted as "call the function 3 with the argument 1-x3" and since 3 isn't a function, you get that error message. I assume you simply forgot a * there.

sepp2k 378 Practically a Master Poster

Because '(foo bar baz) is the same as (list 'foo 'bar 'baz) and since numeric constants are self-evaluating, '2 and '3 are just equal to 2 and 3, so the whole thing comes out as (list 2 '+ 3) (i.e. a list containing the number 2, the symbol + and the number 3).

So if that's your input, you'll need one of those options that I mentioned - or just a boring list of conditions like (equal? op '+), (equal? op '-) etc.

sepp2k 378 Practically a Master Poster

Ideally you'd make it so that the list contains + instead of '+ in the first place. If that's not possible (because you have no control over the lists), you could either use eval or a map or associative list that maps the symbols to their corresponding functions depending on your exact needs.

sepp2k 378 Practically a Master Poster

You can call a function that gets each piece, but your getOperator function needs to return +, not '+. For example this would work:

(define (get-operator expression)
  (cond
    ((some condition) +)
    ((other condition) *)
    (...)))

But this will not:

(define (get-operator expression)
  (cond
    ((some condition) '+)
    ((other condition) '*)
    (...)))

PS: The naming convention in Scheme (and Lisps in general) is to separate words in a name by -, not camel case. So getOperator would more idiomatically written as get-operator.

sepp2k 378 Practically a Master Poster

It's not quite clear to me, what you're trying to do here. If you want the division to only happen if x = 1 is false, it should be inside the else block of the first if. Also every if needs an else, so your first if causes a syntax error because it doesn't.

Also if x is supposed to be the result of the division, why do you already use it on line 2 when the division hasn't happened yet? Further to define a local variable, you'd use let, just writing x = value is not syntactically valid. If you want to change the value of an already existing int variable named x, you can't do that. Variables in SML are immutable. If you want to simulate mutable variables, you can use an int ref instead. But you probably shouldn't.

It also seems strange that your hello function does not take any arguments. Or that both operands to the division are constant (why not just write x = 2 then?).

Here's something that I think might be close to what you might want:

fun hello x =
    if x = 1 then true
    else
        let
            val y = 10 div x
        in
            if x = 4 then true
            else false
        end;
sepp2k 378 Practically a Master Poster

factorial(10) is just an unidiomatic way to write factorial 10, i.e. it calls factorial with the number 10 as its argument. The reason that it works is that it's legal to surround any expression with parentheses. For the same reason it would also be legal to write val x = (10) instead of val x = 10 or (10) + (4) instead of 10 + 4.

When you write find (3, [1,2,5]), you're calling find with the tuple (3, [1,2,5]) as its argument. Since the argument to find can be of any type, SML accepts this and simply remembers that ''a (the type of the argument to find) is int * int list, i.e. a tuple containing an integer and a list of integers. Since the return type of find is ''a list -> bool and ''a in this case is int * int list, that means that this call to find will return a function of type (int * int list) list -> bool as its result, which clearly isn't what you want.

As I said, you need to decide when you define a function (that needs more than one argument) whether you want it to take its arguemnts in form a tuple of arguments or whether you want it to be curried and then you need to call it that way.

sepp2k 378 Practically a Master Poster

You're defining your function as f x y, so it's a curried function of type ''a -> ''a list -> bool. However you call it recursively as f (x, tl y), so you call it with a tuple as its argument.

If we insert a tuple ''b * ''b list as ''a into the type signature, we get (''b * ''b list) -> (''b * ''b list) list -> bool, so the expression find (x, tl y) has the type (''b * ''b list) list -> bool. However it should just have the type bool. Therefore you get a type error.

To fix your issue you should either call your function as a curried function (find x (tl y)) or define it as a tupled function fun find (x,y) = .... You can't define it as one and call it as the other.

sepp2k 378 Practically a Master Poster

As the error message says, input only expects a single argument (or none), but you give it three. The print function can take multiple arguments and will then just print one after the other (on the same line). The input function does not do that - you have to call it with a single string.

To create a single string for your prompt, you can use the format method like this:

action = input("Trade number {} (buy/sell)?".format(i))
Gribouillis commented: indeed +14
sepp2k 378 Practically a Master Poster

I'm not sure what you mean. If you want to put your member functions into your vector, you need to change the type of your vector (and then also change the calls when you call the functions). An example of this would be:

class CPerson
{
        public:
                CPerson(void) {};
                ~CPerson(void) {};
                typedef std::function<bool(CAle&, CPerson*, CPerson*)> FUNCTIONPOINTER;
                vector<FUNCTIONPOINTER> fp_Sip;
};

int main(void)
{
        // ...
        for (auto it = Person.fp_Sip.begin(); it != Person.fp_Sip.end(); ++it)
                (*it)(Ale, pP1, pP2);
        Person.fp_Sip.at(enSip3)(Ale, pP1, pP2);
}

If you don't want that, you need to bind the first argument using std::bind.

PS: Note that there's a lot of undefined behavior in your program as your bool functions don't actually return a value and you don't initialize your pointers.

PPS: The return value of main should be 0 - not 1 - when your application exits successfully.

sepp2k 378 Practically a Master Poster

Are you sure you don't get any errors on the lines where you call push_back? Because that's where I would expect errors to happen.

Anyway the problem I see is that your functions are member functions of CAle and thus need to be called on an object of type CAle. By wrapping them with mem_fn you're creating a function object that takes three arguments: an object of type CAle on which to call the function and two CPerson pointers to pass as arguments. However your vector is supposed to store functions/function objects that take two arguments, not three, and the first argument is supposed to be of type CPersion*, not CAle.

sepp2k 378 Practically a Master Poster

Currently you have a regex that matches the whole string and then replace that with 'a'. So the whole string is going to be replaced with a single 'a'.

If all you want is to replace every character with one 'a' per character, just use a regex that matches a single character. If there are no special requirements on the characters, you can just do:

result = re.sub('.', 'a', 'Cat')

The count = 0 is unnecessary because that's the default.

sepp2k 378 Practically a Master Poster

But execfile('func.py') produced no such error?

If both files are in the same directory, I don't know why it wouldn't work. If they aren't exefile shouldn't have worked either. So my only idea is that you maybe accidentally somehow moved the files into different directories when you replaced execfile with import - or you created a new file to test import and that file is in a different directory than func.py.

sepp2k 378 Practically a Master Poster

In Python a variable is defined when you first assign something to it. In your code you never assign anything to y, so it is not defined. You can not use variables that are not defined. As you already figured out, assigning something to y before the loop defines y and thus fixes that error.

Your other problem is that you assign y to be an empty list. For any list y, writing y[i] (whether it's to read from that position or write to it) is only legal if i is a valid index for the list. A valid index for a list of size n is either a non-negative integer less than n or a negative integer greater than or equal to -n. So since your list has a size of 0, there are no valid indices for it (a number can't be less than 0 and non-negative at the same time nor can a negative number be greater than or equal to 0). In other words: it's never legal to write y[i] if y is an empty list.

To add elements to a list you use the append method like y.append(x[-(i+1)]. This adds the given element to the end of the list, increasing its size by one.

Edit: God, I type slowly.

sepp2k 378 Practically a Master Poster

It's just import func - import func(func) isn't legal syntax in Python. Other than that: yes, like that.

sepp2k 378 Practically a Master Poster

The return value of execfile is always None. All it does is to execute the code in the file. It does not check whether the last statement in the file is an expression and if so return its value or anything like that.

If you want to use func's return value, you should remove the call to func from func.py, import func (or from func import func in your calling code and then call func.func(z) (or just func(z) if you used from) in that file.

Since your func.py can't stand on its own anyway (z wouldn't be defined if you tried to run it directly), I assume that removing the call won't be a problem.

sepp2k 378 Practically a Master Poster

You can also use for animal, noise in instead of for tpl in. Then you can use animal and noise instead of tpl[0] and tpl[1] respectively.

M.S. commented: thanks :) +4
sepp2k 378 Practically a Master Poster

I'm guessing you're using Python 3.x where print() takes exactly one argument.

That's not true. In Python 3 print takes arbitrarily many arguments. Further the OP's code won't work in Python 2 either.

The syntax to call print (or any other function) with multiple arguments in Python 3 is print(arg1, arg2, etc). In Python 2 it's print arg1, arg2, etc. So the difference is the lack of parentheses. In either case print (arg1)(arg2)(etc) is wrong.

In Python 2 it is interpreted as calling arg1 with arg2 as its argument and then calling the result of that with etc as its argument and then printing the result. Of course that only works if arg1 is a function (or other callable object) and arg1(arg2) also returns a function (or other ...).

In Python 3 it is interpreted as calling print with arg1 as the argument, then calling the result of that with arg2 as the argument and then calling the result of that with etc as the argument. Since the result of print(arg1) is None (no matter what arg1 is), this will lead to the error message that the OP is getting.

sepp2k 378 Practically a Master Poster

The construct template<typename T> is used to paramatrize classes, structs, unions, functions or, in C++ 11, type aliases with type parameters (or in some cases other compile-time parameters). So template<typename T> must be in front of the definitions of one of those things (like template<typename T> class Foo {...}). In your case it's inside a function body, which is not allowed.

It's not clear what you want parametrize here. If you wanted to parametrize main, you'd need to write template<typename T> int main(), except that it's not legal for main to be a template function because main is called by the operating system and the OS would not know which type to supply as an argument.

So you'd need to define your own function template<typename T> mymain(), put the code in there and then call that from main with the appropriate type argument. Except that won't work either because:

T one = "test";
T two = 255;
T three = 287.52;
T four = 'x';

Those four variables can't have the same type (unless there's a custom defined class with implicit constructors accepting each of the four types, but in your code there's not).

It's important to understand that in any given instantiation of a template, all occurrences of T refer to the same type. So if call, say mymain<int>() and mymain contains the above code, it will behave like you wrote:

int one = "test";
int two = 255;
int three = 287.52;
int four = …
sepp2k 378 Practically a Master Poster

I still need to set a global variable because It carrys over function calls

No, you don't; local variables that are closed over from an outer function do carry over between function calls. Look at this:

def memoize(f):
    cache = {}

    def wrap(x):
        print("Contents of cache: {}".format(cache))
        if x not in cache:
            print("Calculating {}({})".format(f.__name__, x))
            cache[x] = f(x)
        return cache[x]

    return wrap

def double(x):
    return 2 * x

def square(x):
    return x*x

mdouble = memoize(double)        
msquare = memoize(square)

print("Double:")
mdouble(3)
mdouble(3)

print("\nSquare:")
msquare(3)
msquare(3)

Output:

Double:
Contents of cache: {}
Calculating double(3)
Contents of cache: {3: 6}

Square:
Contents of cache: {}
Calculating square(3)
Contents of cache: {3: 9}

As you see both msquare and mdouble have their own cache and those caches persist between calls to msquare and mdouble respectively. So this acts exactly like you want without any globals.

sepp2k 378 Practically a Master Poster

If a function is nested in another function, you're not allowed to use unqualified exec in either of the two functions. Unqualified in this case means "without in". An explanation of why this limitation exists can be found here.

In your code you don't really need exec. To set and get global variables by name, you can just use globals()[name], but you don't even need global variables either. You can just define cache and rankings as local variables in mu_cache and then access them in wrap.

Another error in your code is that you use global rankings in delete_smallest. This will cause an error message about there being no global variable named rankings because rankings is a local variable in the wrap function, not a global variable. If you just remove that line, the error will disappear and you will be correctly able to access the rankings variable.

Gribouillis commented: very good remarks +14
sepp2k 378 Practically a Master Poster

Now i wanted it to sort using bubblesort and structures.

Why? Unless you have a very goood reason not to, you should really use std::sort. And even if you do have a very good reason, I don't see why you'd want to use bubble sort instead.

I also don't see why you put your sort function in a class if the class doesn't actually contain anything.

sepp2k 378 Practically a Master Poster

I removed the /g

You mean "added", right?

sepp2k 378 Practically a Master Poster

It means if stdout is writing normally to the screen, it will automatically be flushed when you print a newline. But when it's writing to, say, a file or a pipe, the file won't be actually written to until the buffer is full, you explicitly flush it or the program ends.

sepp2k 378 Practically a Master Poster

When people talk about stdout being line-buffered, that means that if you do printf("Hello ");, then wait for some seconds and then printf("world!\n");, the output will appear all at once as "Hello world!" when the couple of seconds are over. If you used stderr instead (or you flushed stdout after the first printf), you'd see "Hello" right away and then a couple of seconds later the rest of the message would appear.

Since your format string ends with a \n anyway, that's not your problem at all. Even using stdout, your message will appear as soon as you print it, so using stderr instead changes nothing (except that it will mess with output redirection and such).

Your problem is that getchar won't return until the user entered a full line - i.e. it won't return right after the user entered the first character. That's not something you can change using only the functionality provided by the C standard. Depending on which platform you're targetting, there are platform-specific functions to do what you want though.

somjit{} commented: thanks :) +3
sepp2k 378 Practically a Master Poster

When you call a function, you need a pair of parentheses. Thus it should next.read_name(), not next.read_name.

Also your read_name is infinitely recursive and can't possibly work. And all it does (other than overflowing the stack) is to write to a local variable that it then never uses - that can't be right.

Another problem is that read_name's return type is void, so you can't use it as an operand to << (or to any other operator or function).

sepp2k 378 Practically a Master Poster

The declaration of get_name says that the return type is string. The definition says that the return type is void.

sepp2k 378 Practically a Master Poster

"GOOD EVENING" is an array of characters. If you take any array or pointer and write p + i, you get a pointer pointing to the address that's i elements after the location that p points to. So in case of an array, arr + i (or i + arr - order doesn't matter) produces a pointer to the element of the array arr at index i.

So 2 + "GOOD EVENING" produces a pointer that points to the second O in GOOD. Adding 6 to that moves the pointer 6 further to the right, producing a pointer that points to the first N in EVENING - same as if you had written "GOOD EVENING" + 8. So you pass a pointer to that N to printf and printf then prints all characters starting at that pointer until the end of the string. So that's why you get NING.

sepp2k 378 Practically a Master Poster

~s.o.s~, I think you overlooked the fact that someboundmethod is never actually called in the james' code. d simply stores a reference to the method someboundmethod of the object returned by foo(). Since that method is bound to the object, the object will live at least as a long as the method is referred to.

sepp2k 378 Practically a Master Poster

Ah, I'm stupid. I though setDataRef was a constructor (I didn't pay attention to the name... or the fact that it had a return type). So, yeah, ignore my answer, you can't use initialization lists with methods. Sorry.

sepp2k 378 Practically a Master Poster

Generally you shouldn't use assignment to initialize your members inside the constructor. As you noticed, it doesn't work. It also calls the default constructor, followed by the assignment operator, which might be needlessly expensive for some classes. Also it won't work if the default constructor or the assignment operator aren't defined for the given class.

Instead you should use initialization lists:

someDataClass &setDataRef(const largeDataType &o) : data(o) {}

Using initialization lists you can initialize references and const members without problems and you can initialize non-references using an constructor you like instead of the default constructor.

sepp2k 378 Practically a Master Poster

Actually everything I said in my post was bullshit because I can't read properly. I thought your variables were strings, not arrays of strings. Sorry about that.

Since they're arrays of strings, all of your assignments should cause errors. You can't put ints into an array of strings (because ints aren't strings), nor can you put arrays of strings into array of strings (because again arrays of strings aren't strings and you can only put strings into arrays of strings).

Array of ints? I don’t think I have learned about that yet

If you define an array, you write T name_of_the_array[N]; where N is the length of the array and T is the type of value you want to put inside the array. If you want to put strings into an array, you write string name_of_the_array[N]; like you're currently doing; if you want to put in ints, you write int name_of_the_array[N]; instead. And if you want to put arrays of strings into your array, you write string name_of_the_array[N][M]; or string* name_of_the_array[N]; (the former stores N arrays that all must have size M and the latter stores N pointers that can point to arrays of any size).

If you want to put multiple types of value into the same array, you're out of luck because you can't do that (except using pointers to the values and casting them, but that's almost certainly a bad idea here and probably beyond what you've currently learned anyway).

It is not clear to …

sepp2k 378 Practically a Master Poster

string a string within a string

Pardon?

int potion = 30;
int hiPotion = 70;
int ether = 20;

item[numItems++] = potion;
item[numItems++] = hiPotion;
item[numItems++] = ether;

I'm not exactly sure what you intend those lines to do, but I guarentee you that they won't do that.

string[index] returns a reference to a char, so the right side of the assignment should be a char. Since ints are implicitly convertible to chars, assigning an int works, but all that does is to create the character with the byte value 30, 70 or 20 respectively. So, assuming ASCII or a superset, that's an unprintable character, followed by F, followed by another unprintable character.

The same applies later in the code when you try to assign other integers (or shorts) to characters of strings.

zidane[cmd++] = magic;
zidane[cmd++] = item;

Strings aren't implicitly convertible to char, so that's why that won't compile. If you want to insert a string inside another, use the insert method.

sepp2k 378 Practically a Master Poster

Your power function takes n and multiplies it with itself m times. What it should be doing is take m and multiply it with itself n times.

Also n should be an int, not a float.

sepp2k 378 Practically a Master Poster

The acual value of true and false is not defined, nor is it guarenteed to be either 0 or 1

Not sure what you mean by "actual value", but converting true to an integer will give 1 and false will give 0. That's defined in section 3.9.1, paragraph 6 (in the C++11 standard, but I'm pretty sure it's the same in C++03 - I just don't have the 03 standard handy right now).

The only way you'd get a bool that prints as 128 is if there's UB being invoked somewhere - presumably due to a missing return statement somewhere in the function.

sepp2k 378 Practically a Master Poster
walls,corner[2] = (' #')

You accidentally typed a comma instead of a period here.

As a result the parser things you want to assign to a local variable called walls as well as to the second element of a variable named corner. Because of this Python now thinks that walls is a local variable and thus produces an error when you try to access it before its value has been set.

sepp2k 378 Practically a Master Poster

That line makes no sense, that's why you don't understand it. As you said, it's casting to int* and then back to char*. It could just as well be written p = p; (or just left out altogether because obviously that's a noop).

Line 7 should be p = (char*) arr;. You need a cast there because only void pointers can be implicitly converted to other pointer types - other pointers or arrays can't (though some (most?) compilers allow it with a warning).

The cast on line 10 doesn't make much sense either. Since p has type char*, this line relies on the int pointer being implicitly converted back to char*, which, as I said regarding line 7, is illegal. And if it was illegal it would be the same kind of pointless to-int*-and-back casting we see on line 8. I.e. it calculates p+1 (using the type char*) and then casts that to int* and then right back to char*. So line 10 is the same as p = p + 1; (except the latter does not rely on an illegal implicit cast).

PS: Your main function is missing a return statement.

sepp2k 378 Practically a Master Poster

And what happened then?

sepp2k 378 Practically a Master Poster

How does it not work? Are you getting a syntax error on the funny print line? What is that line supposed to accomplish? That's not a valid use of print.

Anyway using an empty infinite loop to prevent the turtle window from closing is a very bad idea (it will cause the Python process to cause 100% CPU usage) and won't work properly anyway. You should simply call turtle.mainloop().

sepp2k 378 Practically a Master Poster

By the way, you could also perform a XOR swap.

Neither pointers nor floats can be operands to ^, so neither of your macros will work with the OP's float pointers.

sepp2k 378 Practically a Master Poster

Hardcoding float* instead of passing it in as a parameter won't make the code compile in Visual Studio, nor will it fix any other problems the macro has. The only thing it will do is make the code less general.

sepp2k 378 Practically a Master Poster

Earlier I tried this code on windows (IDE = visual studio), It was giving following errors:

The problem is that in C89 you're only allowed to declare variables at the beginning of a block. No further variable declarations are allowed after the first non-declaration in a given block.

So this would be legal:

int main() {
    int x = 7;
    int y = 8;
    return 0;
}

But this would not:

int main() {
    int x;
    x = 7;
    int y = 8;
    return 0;
}

Because here line 4 is a declaration, but line 3 isn't. If you put the declaration of y in a new block, it's legal again:

int main() {
    int x;
    x = 7;
    {
        int y = 8;
        return 0;
    }
}

So to fix your code sample, you can either initialize p and q on line 7 and remove lines 8 and 9, so that the declaration of t is still at the beginning of the block - or you could add braces around the body of your macro, so that it creates its own block.

The latter is much preferable because it allows you to use the macro in the middle of a block - not just at the beginning - and it limits the scope of the t variable, so that you can use SWAP multiple times in the same scope and even in a scope where there's already a variable named t

sepp2k 378 Practically a Master Poster

No, it shouldn't. float* t; is a perfectly legal variable declaration in C - float* = t; is not.

sepp2k 378 Practically a Master Poster

Use the sum function.

sepp2k 378 Practically a Master Poster

But doesn't c's memory address contain value of a+b?

Yes, after it has been assigned. A better example might be f(a+b) where f takes an int reference. Since the result of a+b is a temporary without an address, the call is illegal, but c=a+b; f(c); would be fine because c is a variable.

if so, why a's address can't be accessed? Isn't supposed to store 3?

It can. But what you're passing to print isn't a. It couldn't possibly be because print wants a MyString, not an int. So what you're passing to print is the result of MyString(a) (which is implicitly applied because it isn't marked explicit). And that result is a temporary object that's not stored in a variable and doesn't have an address. If you store it in a variable first, there will be no problem:

MyString a_as_string(a);
print(a_as_string); // Works fine even with a non-const reference

That said, print really should take a const reference because it doesn't modify its argument and there is thus no reason for it to take a non-const reference.

Also your MyString constructor really should be explicit because it makes no sense for an integer n to be implicitly converted to an empty string of size n.

sepp2k 378 Practically a Master Poster

How to change the end of std::string?

You mean remove the last part of the string? Use erase for that.

One way that I could think of is to assign '\0' to all the trailing characters of the string but it would be inefficient to do so if length of string is large.

std::strings are not 0-terminated. Setting their characters to \0 does not make them shorter.

sepp2k 378 Practically a Master Poster

As you noticed, feeding a string that doesn't represent an integer (like "done") to int will cause an exception. So you should only call int on the user input if it is not "done". You can achieve this by putting the if above the call to int and put the call to int in the else part of the if.

PS: Instead of str("done") you can just write "done".

PPS: Note that writing "done" will currently only cause the sum to be printed -- it will not stop the loop from further asking for input.

sepp2k 378 Practically a Master Poster

Make alert virtual and override it in class b.

sepp2k 378 Practically a Master Poster

Instead of defining a new variable with the same name, you could just assign a different value to the same variable, like this:

public class a
{
    protected string text = "class a";
    public void alert()
    {
        MessageBox.Show(text);
    }
}

public class b : a
{
    public b() {
        text = "class b";
    }
}

This way a b object will only have one variable named text, which will be the one inherited from a (and thus also the one accessed by a methods). And the value of that variable will be "class b" for b objects and "class a" for a objects.

TheApex commented: you explained it better +0