C++中类似Python列表的东西
我刚开始学习C++和C++ Builder,之前一直在用Python。现在我在做一个项目,需要一些帮助。
我想找一个和Python里的列表(list)一样的类型。我试过使用向量(vector),但对我来说效果不好。我需要一个可以存储随机数据的变量。我用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个问题,我希望它能问我一个问题(问题的编号),然后我点击一个按钮表示我的答案是对的,另一个按钮表示我的答案是错的!
这是代码:
//---------------------------------------------------------------------------
#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 个回答
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