0

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.

shn
  • 79
  • 1
  • 8
  • 2
    "vector subscript out of range" probably means you're trying to access an index that's out of range. Which means that the code you've shown (which has no statements that access from the vector at all) probably isn't responsible for this. – scohe001 Oct 14 '19 at 16:22
  • 2
    Take up Visual Studio's offer to allow you to debug. Use the call stack, usually in the bottom right of the Visual Studio window, to find out where in your code you asked the `vector` for an invalid value. Determine why the program used an invalid index value and fix it. The last step is the hard part. The first two should take you no effort at all. – user4581301 Oct 14 '19 at 16:25
  • Ok but call stack is empty. – shn Oct 14 '19 at 17:17
  • scohe001 thanks, I have already read the error. But I can't understand why it gives this error when pushing it back with timing outside the for loop. I want to understand the logic of this. – shn Oct 14 '19 at 17:23

1 Answers1

0

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

Kelidon
  • 228
  • 1
  • 12
  • I guess it's not about the clock. I did the same thing by providing the number by entering the condition. The problem hasn't changed. Code: https://pastebin.com/YQz5j8fG – shn Oct 14 '19 at 19:31