c++(类似于python列表)

C++ (something that is like a python list)

本文关键字:列表 python 类似于 c++      更新时间:2023-10-16

我是c++和c++ Builder的新手;我以前用python工作。我正在做一个项目,需要一些帮助。

我正在寻找一种与Python中的列表相同的类型。我试过向量,但对我来说效果不太好。我需要一个可以存储随机数据的变量。我用rand()来得到数字但这些数字并不总是不同的它们会重复。所以我尝试了BoxList,它可以在其中存储项目。我是用Python写的,这样你们就能明白我想对你们说什么了。

import random
pool= list()
for number in range(1,11):
    pool.append(number)
random.shuffle(pool)
print(pool)

这将给我:

    [6, 2, 10, 8, 9, 3, 7, 4, 5, 1] # or some other random shuffled numbers

另一个想法是,我可以检查我正在寻找的随机数是否在BoxList中,但我不知道如何做到这一点。

编辑:我在c++ builder工作,我有问题,让数字进入我的列表框。

我在做一个简单的程序来帮助我学习。我有100个问题,我想让它问我一个问题(问题的数量),如果我的答案是对的,我就按一个按钮,如果我的问题是错的,我就按另一个。

gui

这是代码:

    //---------------------------------------------------------------------------
    #include <fmx.h>
    #pragma hdrstop
    #include <vector>
    #include <iostream>
    #include "Unit3.h"
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
    #pragma resource "*.fmx"
    TForm3 *Form3;
    int right = 0;
    int wrong = 0 ;
    int allQuestions = 0;
    int currentQuestion = 0;
    int toTheEnd = 0;
    std::vector<int> asked;
    //---------------------------------------------------------------------------
    __fastcall TForm3::TForm3(TComponent* Owner)
    : TForm(Owner)
    {
    }
   //---------------------------------------------------------------------------
   void __fastcall TForm3::Button3Click(TObject *Sender)
   {
    allQuestions = Edit1->Text.ToInt();
    right = 0;
    wrong = 0;
    Label1->Text = allQuestions;
    toTheEnd = allQuestions;

   }
  //---------------------------------------------------------------------------
  void __fastcall TForm3::Button1Click(TObject *Sender)
 {
    right += 1;
    toTheEnd -= 1;
    Label1->Text = toTheEnd;
    Label3->Text = right;
 }
//---------------------------------------------------------------------------
void __fastcall TForm3::Button2Click(TObject *Sender)
{
    wrong += 1;
    toTheEnd -= 1;
    Label1->Text = toTheEnd;
    Label2->Text = wrong;
}
//---------------------------------------------------------------------------

我希望你们能理解我想说的,如果不是,请告诉我。

我不清楚为什么std::vector不会为您工作,因为它具有与python的列表类型非常相似的属性。

#include <iostream>
#include <vector>
#include <algorithm>
int main() {
    std::vector<int> pool;
    for (int i=1; i<11; ++i)
        pool.push_back(i);
    std::random_shuffle(pool.begin(), pool.end());
    for (std::vector<int>::const_iterator i = pool.begin(); i != pool.end(); ++i)
        std::cout << *i << " ";
    std::cout << "n";
    // Or, you could print this way:
    for (int i=0; i<pool.size(); ++i)
        std::cout << pool[i] << " ";
    std::cout << "n";
}

这段代码输出:

[7:47am][wlynch@watermelon /tmp] ./ex
6 10 7 4 8 9 5 2 3 1 
6 10 7 4 8 9 5 2 3 1