C ++(类似于python列表的东西)

时间:2014-06-27 12:43:26

标签: python c++ list vector

我是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中工作,我遇到了输入我的ListBox号码的问题。

我做了一个简单的程序,可以帮助我学习。我有100个问题,我想问我一个问题(问题的数量)然后如果我的答案是对的,我点击一个按钮,如果我的问题是错误的话,我点击另一个。!

the 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;

}
//---------------------------------------------------------------------------

我希望你知道我想在这里说什么,如果不是,请告诉我。

1 个答案:

答案 0 :(得分:4)

我不清楚为什么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 
相关问题