Search code examples
c++vectorsfml

vector push_back with clock?


With Vector I can do push_back in a normal way in the for loop, but it's getting very fast. I'm trying to coding it, but I'm getting a few bugs. No error when is no timing. I couldn't fix it and couldn't find it on the Internet.

while (window.isOpen()) {

    Time time = clock.getElapsedTime();
    second = time.asSeconds();

    for (int i = 0; i < randx.size(); i++) {
        rect.setPosition(rand() % 300, rand() % 500);
        if (second == 2) {
            rectshape.push_back(rect);
            clock.restart();
        }
    }

The error I got when I run the program.


Solution

  • It looks like all the cycle's iterations will be done before the value of 'second' would be equal to '2'

    So you could probably use kinda sleep function instead of your 'if', try info from this question for instance

    Also, if you don't want to sleep all the program, check the correct answer from there

    UPD: I've taken correct answer's code and changed it for vector's push_backs. It works as you want I reckon

    #include <stdio.h>
    #include <time.h>
    #include <vector>
    #include <iostream>
    using namespace std;
    
    const int NUM_SECONDS = 2;
    int main()
    {
       int count = 1;
    
       double time_counter = 0;
    
       clock_t this_time = clock();
       clock_t last_time = this_time;
    
       vector<int> vect;
    
       while (true)
       {
           this_time = clock();
    
           time_counter += (double)(this_time - last_time);
    
           last_time = this_time;
    
           if (time_counter > (double)(NUM_SECONDS * CLOCKS_PER_SEC))
           {
               time_counter -= (double)(NUM_SECONDS * CLOCKS_PER_SEC);
               vect.push_back(count);
               cout << count;
               count++;
           }
    
       }
    
       return 0;
    }
    
    

    try it