Я пытаюсь переключить элементы вектора класса с помощью указателей. Я не использую этот метод просто для решения небольшой проблемы, но просто для того, чтобы практиковать этот метод для более сложных проблем.
Вот мой код
#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);
Чтение некоторых документов об использовании вектора сначала было бы достаточно полезным.