矢量 push_back 与时钟?
vector push_back with clock?
使用 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();
}
}
看起来所有循环的迭代都将在 'second' 的值等于 '2'
之前完成
所以你可能会使用有点睡眠功能而不是你的 'if',试试来自 this question 的信息,例如
此外,如果您不想休眠所有程序,请检查正确答案from there
UPD:我已经采用 correct answer's code 并将其更改为向量的 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> 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;
}
试一试
使用 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();
}
}
看起来所有循环的迭代都将在 'second' 的值等于 '2'
之前完成所以你可能会使用有点睡眠功能而不是你的 'if',试试来自 this question 的信息,例如
此外,如果您不想休眠所有程序,请检查正确答案from there
UPD:我已经采用 correct answer's code 并将其更改为向量的 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> 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;
}
试一试