It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I've been reading the Boost C++ documentation and trying to figure out how to generate a random real number between 0 and 1, using the uniform_01 part of the library. Does anyone have any suggestions?
Based on suggestions, I'm using this code, but it generates the same random value every time.
double random01(mt19937 & generator)
{
uniform_01<mt19937> dist(generator);
return dist();
}
int main()
{
mt19937 generator(time(0));
for (int i = 0; i < 10; i++) {
cout << random01(generator) << endl;
}
return 0;
}
Sorry if I wasn't clear; this question isn't solved, by my answer or any other. It's still generating the same random value each time.
There are a few 'gotcha's in this code:
The random01() function does not take a reference to the generator, but rather a copy of the generator. So if you call the function multiple times with the same generator - it will produce the same value over and over again!
The static uniform_01 in random01() only gets initialized on the first call to random01, so if it is ever called with a different generator, it will not use it, but rather use a reference to the first generator, which may even have been destroyed, since!
Correct would be something like following (note the & in the arguments list, for pass-by-reference, and the lack of static:
double random01(mt19937 & generator)
{
uniform_01<mt19937> dist(generator);
return dist();
}
This is the solution I found:
#include <iostream>
#include <ctime>
#include <boost/random.hpp>
using std::cout;
using std::endl;
using boost::mt19937;
using boost::uniform_01;
double random01(mt19937 generator)
{
static uniform_01<mt19937> dist(generator);
return dist();
}
int main()
{
mt19937 generator(time(0));
cout << random01(generator) << endl;
}
The code is slightly modified from here; hat tip to Bojan Nikolic.
I posted this as a "solution" in the hope that it helps someone, but please criticise anything you notice wrong with it. I tried to separate the seeding step from the actual generation so the twister isn't seeded every single time it generates a value.
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I think the title makes it self explanatory. The actual code is quite long but here's and example that I think matches the problem.
#include <iostream>
using namespace std;
char multiDArray [5][5];
multiDarray[1][2] = 'x';
char barrier = 'x';
int main () {
if (multiDArray[1][2] == barrier) {
cout << "It works". }
}
This doesn't give me an error, but nothing happens when I run the program.
Thanks for your help.
I have modified the code you provided so that it compiles:
#include <iostream>
using namespace std;
char multiDArray [5][5];
char barrier = 'x';
int main ()
{
multiDArray[1][2] = 'x';
if (multiDArray[1][2] == barrier) {
cout << "It works";
}
return 0;
}
You'll see here (http://ideone.com/MFn9yM) that it does indeed work.
Output:
It works
It's possible you are seeing no output in your larger program because you are not flushing the output buffer (using std::flush or by including a newline).
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I feel so lost trying to figure this out. I have my own data structure that I am planning on using vectors to avoid having to keep track of free space and reorginization that I would need to do if I used a simple array. I don't don't know if I'm just not initializing properly or what, but every assignment I do seems to just disappear into thin air.
Here is some simple code to illustrate what I'm talking about:
#include <vector>
#include <iostream>
using namespace std;
struct node
{
int test_int;
bool test_bool;
};
struct file
{
vector<node> test_file;
};
int main()
{
file myfile;
int myint;
cout << "Enter number: ";
cin >> myint;
myfile.test_file[0].test_int = myint;
cout << "Number entered is: " << myfile.test_file[0].test_int << endl;
return 0;
}
So basically it is a vector inside a struct. It seems that the normal ways to access a vector don't seem to work, as in I can't read or write anything to the vector however things like myfile.test_file.size() seem to work (as in they return a '0' from a freshly created struct). Trying to access the index directly by myfile.test_file[0].test_int results in a runtime error of vector subscript out of range as if it isn't actually there.
Am I not initializing it properly? This seems kind of ridiculous to me and I can't understand why it wouldn't work that way.
Edit:
Edited code to more clearly show behavior I'm referring to. This compiles but gives a runtime error vector subscript out of range
The edited version doesn't work because you're accessing an element past the end of the vector:
myfile.test_file[0].test_int = myint;
Before you can do this, you need to either resize() the vector, or add an element using push_back():
myfile.test_file.push_back(node());
myfile.test_file[0].test_int = myint;
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I am implementing a recursive solution to the Cracker Barrel Puzzle.
My recursive function returns a string representation of the state of the solved board and all the steps leading to that state.
At each stage in my recursive function, a valid gameboard is generated and the function is recursively called on the gameboard object.
My problem is: what do I need to return when there are no valid gameboard moves that can be made on the current gameboard object? Currently this scenario is causing the function to crash.
Well you have the problem of determining the base case. For mathematical recursive functions, the base case is trivial, like F(0) for the case of Fibonacci Numbers.
Although, I am not familiar with that game or your exact implementation, if you reach a state when no more recursive call would arise, return a Base value. For numbers, it would be the base value, for strings a zero length string. For the case of Gameboard, use a Default state for every cell to indicate that this is a base case and handle that appropriately on the return.
There are many ways to implement recursive functions. Without any hits as to how you have decided to go (you have hinted that you are returning the game state in a string... std::string?), maybe you simply need an if statement:
std::string recursive_game(std::string &populate)
{
if (...game is finished...) {
...
return populate;
} else {
...
return recursive_game(populate);
}
}
int main()
{
std::string completed_game;
recursive_game(completed_game);
return 0;
}
it seems you have to test your return value and throw an exception in case you can't return a correct value.
you can try adding a sanity check function
void main ()
{
bool validMovesAvailable =true;
string currentMoves;
do
{
currentMoves = doNextMove (currentMoves); //your current function
validMovesAvailable = checkAnyMoreMoves (currentMoves); //sanity check function
}while (validMovesAvailable);
}
You return the number of pegs left on the board. This is the score of the game.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
This is probably a basic question.
I have a vector of a data type 'player' that I have defined myself using a struct:
struct player {
string player_name;
string label;
...
...
}
I then having a function taking a vector of these player data types as a parameter and I want to access the members in the struct i.e.
void foo(vector<player> players) {
cout << players.at(0).player_name;
}
The at(i) works because it is a function of vector. However, I can't access player_name. Why is this and how can I solve it? Apologies if this is basic and boring.
Following code accesses player in vector:
#include <string>
#include <vector>
using namespace std;
struct player {
string player_name;
string label;
};
int main() {
vector <player> p;
p.push_back( player() );
p.at(0).player_name = "fred";
}
Your problem is that foo() returns but you don't see the side-effect of the changed player_name, I guess?
It's because you've passed the vector to foo() by value rather than reference. foo() is operating on a copy of the vector rather than whatever original you passed to it, so the player_name change is lost when the function ends.
Try changing the function signature to void foo(vector<player>& players).
(Note that I've added an ampersand to make the parameter a reference.)
You should not get a compilation error since the code you posted is fine. If you are getting a runtime-error make sure you have inserted at least one object into the vector before you try to access it.
just speculation
if you get a compile error:
probably you declare a class instead of a struct.
if you get a runtime error:
the vector is empty
no error but not result:
you haven't flush the stream. Add std::endl or call std::cout.flush()
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 13 years ago.
Recently while surfing some C++ blogs, I came across a small C teaser program in one of them.
#include<stdio.h>
int find_addr()
{
/*fill your code here*/
}
int main()
{
int i,j;
clrscr();
find_addr();
return 0;
}
The question is to find the address of variables i & j without touching the main function. I haven't been able to figure it out yet. Feels awful that I couldn't even solve this minor question :((.
EDIT:
The above program had lot of non-standard statements like the use of inclusion of conio.h anbd other non standard headers and its functions , getch() and other statements, I edited it in a hurry and forgot to omit void from void main(), apologies for that.
EDIT2: I have given my one vote to close this thread since I perceive through the responses posted here that there are non-standard issues related to the question.
I think I found where you read the puzzles. Most of the programs use typeless main(), or worse, void main(). They assume a lot of system- and/or compiler-specific things. The programs on the page are not very good quality, and make for a bad tutorial. Please stay away from it.
For example, this is the first program:
what is the output? Definitely the output is not what you think! so think more..
main()
{
int i = 300;
char *ptr = &i;
*++ptr = 2;
printf("%d",i);
getch();
}
Third program:
what is the output of the following code if array name starts with 65486?
void main()
{
int num[] = {10,11,12,13};
printf("%u %u",num,&num);
}
I could go on, but there is no need really. As I said, stay away from this page!
I think it could look like the following, but it is not conformant way and you shouldn't use it in practice.
int find_addr()
{
int t;
int* i_addr = &t - <some platform&compiler&whatever specific constant>;
int* j_addr = &t - <some platform&compiler&whatever specific constant>;
}
The idea is that i and j are placed on the stack and you could find address of stack by using address of one more variable on the stack.
You should note that sometimes it is impossible to find addresses of i and j because compiler will not allocate memory for them because of optimization. This once again confirms the fact that you should not try to write such code.
On windows this can be done using the _AddressOfReturnAddress intrinsic. This function gives you the address on the stack which contains the return address. the address of i,j would be a constant negative offset from that address.
Notice that any such "solution" is highly non portable and would probably fail in many cases. one such case is if the compiler decides for some reason to make i and j registers. The compiler may decide to do this since you never explicitly take the address of i or j so as far as it is concerned, its safe. In this case i,j don't actually have addresses so you're going to get the address of something else on the stack and writing on it is very likely to crash your program.
I found this works in VC compiler..
the function name takes 2 int32 in the stack, then comes the definition of a.
int find_addr()
{
int a;
printf("&a = %u &i = %u & j = %u\n", &a, &a+4, &a+3);
}