带有时钟的向量push_back? [处于保留状态]

问题描述 投票:0回答:1

使用Vector,我可以在for循环中以正常方式执行push_back,但是它变得非常快。我正在尝试对其进行编码,但是却遇到了一些错误。没有时机就没有错误。我无法修复它,也无法在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.

c++ vector sfml
1个回答
0
投票

似乎所有循环的迭代都将在'second'的值等于'2'之前完成

因此您可能可以使用某种睡眠功能而不是'if',例如尝试从this question获得的信息

此外,如果您不想休眠所有程序,请检查正确答案from there

UPD:我已将correct answer's code更改为vector的push_backs。我认为它可以按您的意愿工作

#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> vector;

   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);
           vector.push_back(count);
           cout << count;
           count++;
       }

   }

   return 0;
}

尝试

© www.soinside.com 2019 - 2024. All rights reserved.