[英]Referencing Elements of Class Vectors using C++
我試圖使用指針切換類向量的元素。 我並不是僅僅為了解決一個小問題而使用這種方法,而是為了解決更困難的問題而練習使用這種方法。
這是我的代碼
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class thing{
public:
int index;
int value;
thing();
private: int number;
};
thing::thing()
{
number = 0;
}
void arrange(vector<thing>* array[]){
for(int i=0; i<19; ++i){
if(array[i]->value<array[i+1]->value){
swap(array[i], array[i+1]);
arrange(array);
}
}
}
int main(){
vector<thing>** things = new thing*[20];
for (int i=0; i < 20; ++i)
{
things[i] = new thing(); // default constructor
things[i]->index = i;
things[i]->value=rand() % 100;
}
cout << "The random array is: " << endl;
for(int i=0;i<20;++i){
cout << things[i]->value << endl;
}
arrange(*things);
cout << "The arranged array is: " << endl;
for (int i=0; i < 20; ++i)
{
cout << things[i]->value << endl;
}
return 0;
}
我認為這就是您想要的:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class thing{
public:
int index;
int value;
thing();
private: int number;
};
thing::thing()
{
number = 0;
}
// This arrange accept array of any length
void arrange(vector<thing *> &array)
{
while(1)
{
int regressed=1;
for(int i=0; i<array.size()-1; i++){
if( (array[i]->value) < (array[i+1]->value) ){
thing * tmp=array[i+1];
array[i+1]=array[i];
array[i]=tmp;
regressed=0;
}
}
if(regressed==1)
return;
}
}
int main(){
vector<thing*> things; // init a container to contain " thing * " type vars
for (int i=0; i < 20; ++i)
{
thing * t = new thing(); // default constructor
t->index = i;
t->value=rand() % 100;
things.push_back(t); // Add vars appended
}
cout << "The random array is: " << endl;
for(int i=0;i<20;++i){
cout << things[i]->value << endl;
}
arrange(things);
cout << "The arranged array is: " << endl;
for (int i=0; i < 20; ++i)
{
cout << things[i]->value << endl;
}
return 0;
}
結果輸出為:
The random array is:
83
86
77
15
93
35
86
92
49
21
62
27
90
59
63
26
40
26
72
36
The arranged array is:
93
92
90
86
86
83
77
72
63
62
59
49
40
36
35
27
26
26
21
15
請記住:
vector<int> varname;
vector<int *> varname;
具有與以下相同的邏輯含義:
int varname[size];
int* varname[size];
但是在向其中添加新元素時,矢量可以自動展開:
vectVar.push_back(sth);
首先閱讀一些有關vector用法的文檔將很有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.