Vector of class pointers - c++

I know that there are several similar questions previously asked. But none of them are answered with wide recognition and the vector of pointers are still very confusing to me.
Here is the code:
Imagine we have a:
vector<member*> vector_member;
for (int i = 0; i < n; i++){
member* mem = new member(i); //constructor
mem->init(); //This function use a random number generator to give the member some randomness
vector_member.push_back(mem);
}
After executing this code, I find that the all the random number for vector_member[i] are the same!
Any experts have any idea about this?

I'd have to see your init method, but my guess would be that your random function is using a seed value like the current time (eg in milliseconds since the epoch) to initialize itself, and your code is executing so quickly that the time hasn't changed between calls, so it returns the same random number.

Related

Why does local variables built by pointers and by objects show different output

I wrote a program to calculate average path length in my red black tree. I found something really weird. The code is shown below:
while (dataSize<MaxSize) {
int i = 0;
double aveLengthArr[1000];
while (i < 1000) {
RedBlackTree rbt;
int* array= generateRandomInput(dataSize);
for (int n= 0; n < dataSize; n++) {
rbt->insert(array[n]);
}
aveLengthArr[i]=rbt->getAvePathLength();
i++;
}
double mean = calAverage(aveLengthArr);
double stdDeviation = calDeviation(aveLengthArr, mean);
dataSize++;
}
When a specific line code RedBlackTree rbt; is used, the average length is still the same with different input array (I have already debugged it).
But when the code is changed to RedBlackTree* rbt=new RedBlackTree;,it get the right result and the length varies.
So I am really confused because rbt is a local variable, right? Every time the program jumps into a new loop, the rbt should be a totally new object. Even if it is not updated, the length should increase but it is not. After using a pointer, it is right.
Another weird thing is that when I run the program with code RedBlackTree rbt; in Window7, the result is right. When using Ubuntu, it shows the problem above.
Any idea is appreciated.It is really hard for me to figure it out.
The RedBlackTree is red black tree and I write it as a self-defined class.Part of the class is showed below:
class RedBlackTree {
private:
Node* root;
int redNodeNum;
int totalPathLength;
public:
RedBlackTree() {
redNodeNum = 0;
totalPathLength = 0;
}
}
You do not initialize root in your constructor.
Every time the program jump into a new loop, the rbt should be a totally new object.
The object is constructed each time. But the memory is probably at the same address each time through the loop (this is not a guarantee). And since you don't initialize root, you're seeing some undefined behavior, which again is probably keeping the last value from the loop...but would be sensitive to conditions of compilation, debugging, optimization...
https://en.wikipedia.org/wiki/Undefined_behavior
Another weird thing is that when I run the program with code RedBlackTree rbt; in Window7, the result is right. When using Ubuntu, it shows the problem above.
This is the kind of thing that happens with undefined behavior.
rbt->insert(array[n])
As #SergeyTachenov has pointed out, this likely won't compile since your RedBlackTree is not a pointer in the given code (so would have to be rbt.insert(array[n]). It is probably an artifact of you copying something halfway between the pointer-based version and the non-pointer based one.
Posting a complete and coherent example is important, so please read about MCVE: Minimal, Complete, Verifiable Examples. The code in your question should ideally compile as-is in an online compiler and clearly demonstrate your problem.

add elements to vector in a loop

the code I have problem is:
vector<int> steps_list;
steps_list.reserve(runs);
for (int i=0;i<runs;i++){
int steps=0;
bool in_con=false;
srand(time(0));
int init_pos=rand()%mylat;
while (in_con==false) {
srand(time(0));
int step=2*(rand()%2)-1;
init_pos+=step;
init_pos=init_pos%grid.size();
if (grid[init_pos]==0){
in_con=true;
}
steps+=1;
}
steps_list.push_back(steps);
}
for (int i=0;i<mylat;i++){
cout<<steps_list[i]<<" ";
}
I want to store in steps_list vector all the different steps ,but instead of that it stores only one step and it fills the vector with that.
I can't figure where is my problem.I am not familiar with vectors.
You need to move this line
srand(time(0));
outside the loop, and preferably do this once at the beginning of your program.
You are seeding the random number generator, and my guess is the time you obtain has second resolution. The loop iterations take less than a second, so you are always seeding with the same value and obtaining the same random numbers.
I'm guessing but the error might be that you call srand(time(0)) before each call of rand(). That's a very good way to make your random numbers completely unrandom.
Could that be an explanation for what you see?
In any case call srand(time(0)) once at the beginning of the program and nowhere else.

C++ STL container ::clear ::swap

What's the fastest way to "clear" a large STL container? In my application, I need to deal with large size std::map, e.g., 10000 elements.
I have tested the following 3 methods to clear a std::map.
Create a new container every time I need it.
Calling map::clear() method.
Calling map::swap() method.
It seems that ::swap() gives the best result. Can anyone explain why this is the case, please? Is it safe to say that using map::swap() method is the proper way to "clear" a std::map? Is it the same for other STL containers, e.g., set, vector, list, etc.
m_timer_start = boost::posix_time::microsec_clock::local_time();
// test_map.clear();
test_map.swap(test_map2);
for (int i = 0; i< 30000; i++){
test_map.insert(std::pair<int, int>(i, i));
}
// std::map<int, int> test_map_new;
// for (int i = 0; i< 30000; i++){
// test_map_new.insert(std::pair<int, int>(i, i));
// }
m_timer_end = boost::posix_time::microsec_clock::local_time();
std::cout << timer_diff(m_timer_start, m_timer_end).fractional_seconds() << std::endl; // microsecond
You aren't properly testing the swap case. You need for the swap-to map to be destroyed in order to account for all of the time. Try one of these:
{ std::map<something, something_else> test_map2;
test_map.swap(test_map2);
} // test_map2 gets destroyed at the closing brace.
or
// temporary gets destroyed at the semi-colon
std::map<int, int>().swap(test_map);
Are you asking this because you're having a performance problem and you have identified that your program is spending too much time clearing your maps? If you haven't done this then just use map::clear() or create new local variables each time, whichever is most natural and direct for your program. The swap trick is an optimization and there's little point in wasting time optimizing unless you're certain you need to, based on experience.
If you have identified a performance issue then you've already got the tool to determine which of your methods best addresses it.

Random Number Generation with Well44497a in C++

Sorry to bother again, but as I am new C++ I am having a lot of weird and silly problems.
I am programing a MCMC method. I read in this forum that the WELL RNG was a good alternative to generate random numbers so I am trying to make it work. So here the questions:
I am compiling the "Well44497a.c" within my c++ project without further modifications. It compiled. Is that right or should I make any change?
I am using the following scheme inside my code but it is just generating a cycle of 3 RN
SOLVED: The problem was that InitWELLRNG44497a(state) should be placed outside the function. I was re initiating the generator every time I was generating a sample. For the whole run the generator has to be initialized just once.
int* sampler(PARAMETERS) { //this function returns a sample
int k;
unsigned int state[1391];
for (k = 0; k < 1391; ++k)
{
state[k] = k;
}
InitWELLRNG44497a(state); //THIS SHOULD GO ON THE CALLER FUNCTION NOT HERE
double value_first = valuate(first_state); // this function valuates one of two possible states
double value_second = valuate(second_state);
double rand_number = WELLRNG44497a()
if(rand_number > value_first / (value_first + value_second))
return second_state;
else
return first_state;
}
Your function appears to initialise the state array with the same values every time you call your sampler() function. The idea of the state array is that it holds the current state of the random number generator, and that you don't fiddle with the contents of state between calls to the RNG.
Make the state array global in your program, initialise it once, and don't touch it after initialisation.

c++ variable declaration

Im wondering if this code:
int main(){
int p;
for(int i = 0; i < 10; i++){
p = ...;
}
return 0
}
is exactly the same as that one
int main(){
for(int i = 0; i < 10; i++){
int p = ...;
}
return 0
}
in term of efficiency ?
I mean, the p variable will be recreated 10 times in the second example ?
It's is the same in terms of efficiency.
It's not the same in terms of readability. The second is better in this aspect, isn't it?
It's a semantic difference which the code keeps hidden because it's not making a difference for int, but it makes a difference to the human reader. Do you want to carry the value of whatever calculation you do in ... outside of the loop? You don't, so you should write code that reflects your intention.
A human reader will need to seek the function and look for other uses of p to confirm himself that what you did was just premature "optimization" and didn't have any deeper purpose.
Assuming it makes a difference for the type you use, you can help the human reader by commenting your code
/* p is only used inside the for-loop, to keep it from reallocating */
std::vector<int> p;
p.reserve(10);
for(int i = 0; i < 10; i++){
p.clear();
/* ... */
}
In this case, it's the same. Use the smallest scope possible for the most readable code.
If int were a class with a significant constructor and destructor, then the first (declaring it outside the loop) can be a significant savings - but inside you usually need to recreate the state anyway... so oftentimes it ends up being no savings at all.
One instance where it might make a difference is containers. A string or vector uses internal storage that gets grown to fit the size of the data it is storing. You may not want to reconstruct this container each time through the loop, instead, just clear its contents and it may not need as many reallocations inside the loop. This can (in some cases) result in a significant performance improvement.
The bottom-line is write it clearly, and if profiling shows it matters, move it out :)
They are equal in terms of efficiency - you should trust your compiler to get rid of the immeasurably small difference. The second is better design.
Edit: This isn't necessarily true for custom types, especially those that deal with memory. If you were writing a loop for any T, I'd sure use the first form just in case. But if you know that it's an inbuilt type, like int, pointer, char, float, bool, etc. I'd go for the second.
In second example the p is visible only inside of the for loop. you cannot use it further in your code.
In terms of efficiency they are equal.