I'm using dlib.
I came across the following in one of the example programs:
cout << "p(D=0) = " << solution.probability(D)(0) << endl;
I've never seen a double parenthesis after a function call in C++. What does it do and how does it work?
What does solution.probability(D) return. If it's a functional object, or a pointer to a function, you can call it, which is probably what the second set of parentheses do.
Related
I am attempting to recreate some "R" scripts in C++, just for the fun of it. Have used C decades ago but not recently. Now what I have is a bit of code where I am reading data from a binary file and placing the data into a structure (or class) with an unknown number of array structures (for the file reading side). Not knowing exactly how many arrays are needed, I define the number after reading another binary file which contains that data. So, I have two options; one to enter new data (which saves that plus the number of arrays to two files); another to read saved data back in (which provides the number of needed array structures). Having done either option via 'IF' conditionals, I need the new or recovered data to perform math on outside those conditionals. This is where things go wrong. The data is not available. The simple example recreates the problem and I have not stumbled upon the solution yet. I am not familiar enough with C++ to find what is most likely something simple to fix. The 'closed' function's first line outside the 'if' conditionals does work as expected, but that's not the data I need, and I don't want that line in the program.
#include <iostream>
using namespace std;
void closed(void);
class traverse {
public:
int sta;
};
int main()
{
closed();
return 0;
}
void closed(void)
{
traverse stations[1]; // removes 'stations was not declared' error on line 35.
cout << "Enter 1 or 2\nSelect: ";
int selType;
cin >> selType;
if (selType == 2) {
cout << selType << " selected\n";
traverse stations[1];
stations[0].sta = 2; //need this member value available outside conditional.
cout << "Value is " << stations[0].sta << " inside." << endl;
} else {
cout << selType << " selected\n";
traverse stations[1];
stations[0].sta = 1; //need this member value available outside conditional.
cout << "Value is " << stations[0].sta << " inside." << endl;
}
cout << "Value is " << stations[0].sta << " outside." << endl;
}
I originally used a 'struct' but decided to try a 'class' to discover the differences. But, the same problem persists with both, so I don't think it is anything with the definitions, but perhaps with different declarations. Any ideas would be greatly appreciated. Thanks.
If you need it to live longer than the scope of the if, then declare it in the outer scope where you need it to continue living.
After you added this line to deal with the warning:
traverse stations[1]; // removes 'stations was not declared' error on line 35.
You left the declaration of stations inside the if. That hides the outer name, and will receive the data, then go out of scope when the brace-enclosed block exits. To put data into the outer stations don't hide it.
If you need this data to live longer than the function call itself, you'll need to pass in an object to be written into, or allocate and return one to the caller. Perhaps a vector? I don't like (or recommend) to pass raw arrays because they decay to pointers and lose the bounds encoding from their type. That makes it too easy to go out of bounds without being very careful. There are smart pointer wrappers you could use, or a span class, etc., to help do it more sensibly.
Hello all c++ noob here,
For my homework in c++ I must create a program that inputs 5 cities and prints them in order and reverse order by the users choice using arrays and seperate functions. The homework requires that you use all these functions to operate. The program runs fine until I enter o or r for reverse order. I get a segmentation error. I think I am printing or passing the strings incorrectly.
Here is my declaration of my array function
void displayInOrder (string o[5]);
Now here is my function with the executable code.
void displayInOrder (string o[5])
{
cout << "Here are the cities in order: " << endl;
cout << o[0] << " " << o[1] << " " << o[2] << " " << o[3] << " " << o[4]
<< endl; //the error seems to lie somewhere in here and the same
//in the reverse function
}
Now in the main I am calling the function like this.
displayInOrder (&cities[5]);
I think I am either calling the function incorrectly, declaring it wrong, or printing it wrong. It's been a while since I programmed in C++ and I am a bit of a noob. I appreciate any help anyone has to offer.
The displayInOrder() function is expecting a pointer to an the whole array. Instead, you passed a pointer to cities[5]. This has two problems:
It's a pointer to a specific element, not the whole array.
The last element of the array is cities[4], so you're accessing outside the array bounds.
You should call the function this way:
displayInOrder(cities);
There's no need to use &, an array variable automatically decays to a pointer when used as a function argument.
I'm reading Inside The C++ Object Model and find confused about inline function expansion.
In general, each local variable within the inline function must be introduced into the enclosing block of the call
as a uniquely named variable. If the inline function is expanded multiple times within one expression, each
expansion is likely to require its own set of the local variables. If the inline function is expanded multiple
times in discrete statements, however, a single set of the local variables can probably be reused across the
multiple expansions.
Here, what does it mean to expand inline function multiple times in discrete statements and how could that happen? Can anyone raise a concrete example to apply this?
I had some trouble to handle the term discrete statement (especially because it has been emphasized multiple times). I tried to find something like a clear definition (by google) but I couldn't. Thus, I decided to read this literally as one statement (with discrete in the sense of separate).
Denoting a function inline is just a hint to the compiler that the programmer would like to have the function body inserted directly at every "call point" (instead of simply calling the function). Actually, the compiler decides whether the function is really inlined. (It might be even inlined at one point of call but become a function call at another point.) If a macro is used instead of the inline function, the inline requirement would be granted (as macro expansion is actually nothing else than text replacement). Of course, macros have a lot of limitations which inline functions have not. One of them is that inline functions may have local variables.
I made a synthetic example. It's not code "ready for production" but it hopefully helps to illustrate the topic:
#include <iostream>
using namespace std;
inline int absValue(int a)
{
int mB = -a;
return a < 0 ? mB : a;
}
int main()
{
int value;
// use input to prevent compile-time computation
cout << "input: " << flush;
cin >> value;
// multiple usages of absValue()
cout << "value: " << value << endl
<< "absValue(value): "
<< absValue(value)
<< endl
<< "absValue(-value): "
<< absValue(-value)
<< endl;
// done
return 0;
}
The second output statement calls function absValue() multiple times where the call should be inlined. I imagine it like:
// multiple usages of absValue()
cout << "value: " << value << endl
<< "absValue(value): "
<< {
int mB = -(value);
return (value) < 0 ? mB : (value);
}
<< endl
<< "absValue(-value): "
<< {
int mB = -(-value);
return (-value) < 0 ? mB : (-value);
}
<< endl;
There are two occurrences of mB in this statement. On one hand, these are two separate local variables. On the other hand, they may share the same storage on stack as they are used consecutively. (They might not share the same storage if the compiler optimization introduces some kind of code re-ordering which results in interleaving of the first and second expansion of absValue().)
This whole explanation is rather theoretically. Practically, the compiler will hopefully put mB into a register or even optimize most of the code away.
I fiddled a little bit with godbolt to illustrate it further. Finally, I must admit that it proofs essentially my last paragraph above.
I feel I'm asking a very basic question, but I haven't been able to find an answer here or in Google. I recall we were taught this at school, but alas it has vanished over years.
Why does cout.precision() (std::ios_base::precision()) affect the whole stream when called in the middle of the output list? I know the rule that std::setprecision() should be used to change precision on the fly, and that cout.precision() is going to spoil the output with the value it returns. But what is the mechanics of this? Is it due to buffering? The manuals state these "do the same thing", but empirically I can see it's not entirely true.
MCVE:
const double test = 1.2345;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << test << endl << cout.precision(3) << test << endl;
// Output:
// 1.234
// 21.234
// after the same init
cout.precision(2);
cout << test << endl << setprecision(3) << test << endl;
// Output
// 1.23
// 1.234
Is this "implementation specific / not defined by the standard"?
Feel free to mark this as duplicate, for I haven't been able to find it on SO.
The order of function argument evaluation is unspecified. When you call std::cout.precision(n) the precision of std::cout' is set at the point this call is evaluated. In your expression
cout << test << endl << cout.precision(3) << test << endl;
the cout.precision(3) is, apparently, called first thing which the compiler is entirely allowed to do. Remember that the compiler considers the above statement equivalent to
std::cout.operator<<(test)
.operator<<(std::endl)
.operator<<(std::cout.preision(3))
.operator<<(test)
.operator<< (std::endl);
Practically, it seems for your compiler function arguments are evaluated right to left. Only then the different shift operators are executed. As a result, the precision gets changed before the output is done.
The use of manipulators like std::setprecision(n) avoids relying on the order subexpressions are evaluated: the temporary created from std::setprecision(n) is created whenever it is. The effect is then applied when the appropriate shift operator is called. Since the shift operators have to be called in the appropriate order, the use of the manipulator happens at a known place.
The exact time when cout.precision(3) is evaluated in your first example is not defined, because its value serves as an argument for a function call. OTOH with the second example, the time when setprecision(3) is inserted to the stream is very well defined - i.e. after endl is inserted and before test (2nd time). Therefor the first version will not produce reliable results (what you get may be different on different implementations), but the second version will.
See this question for a more detailed explanation. (The question there doesn't use operators, but the principle is the same - calling a member function on the return value of another function.)
I have a custom stack class. Most of the code can be seen here:
Member functions of a templated class, that take a template type as argument
I fill the stack like so:
stack <int> Astack;
Astack.Push(1); Astack.Push(2); Astack.Push(3); Astack.Push(4);
Then I do this:
cout << Astack.Pop() << Astack.Pop() << Astack.Pop() << Astack.Pop() <<endl;
and get this: 1234
However, if I do this:
cout << Astack.Pop(); cout << Astack.Pop(); cout << Astack.Pop(); cout << Astack.Pop();
I get this: 4321, which is obviously what I want.
So, what gives?
The order of evaluation of the function calls is unspecified. Your first expression basically boils down to this:
cout << a << b << c << d;
Each of a, b, c, and d are calls to Astack.Pop(). The compiler can generate code that evaluates those calls in any order it chooses.
You should avoid writing expressions that rely on a particular order of evaluation of parts of the expression. In general, it's not safe (and even when it is safe, it is usually quite confusing).
In the first version the arguments to cout are evaluated from right to left. You never actually specify which order they should be evaluated in, so the one on the right is evaluated first, popping the 4, and so on.
There is something known as Unspecified Behaviour defined by the ISO C++ Standard. Your code-snippet is just an example of that.