[英]Referencing Elements of Class Vectors using C++
I am trying to switch the elements of a class vector using pointers. 我试图使用指针切换类向量的元素。 I am not using this method simply to solve a small problem, but just to practice using this method for more difficult problems.
我并不是仅仅为了解决一个小问题而使用这种方法,而是为了解决更困难的问题而练习使用这种方法。
Here is my code 这是我的代码
#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;
}
I think that is what you want: 我认为这就是您想要的:
#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 result output is : 结果输出为:
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
Remember that: 请记住:
vector<int> varname;
vector<int *> varname;
has the same logical meaning as: 具有与以下相同的逻辑含义:
int varname[size];
int* varname[size];
but vectors can be expanded automatically when you add new elements into it: 但是在向其中添加新元素时,矢量可以自动展开:
vectVar.push_back(sth);
Reading some docs about vector's usage first would be helpful enough. 首先阅读一些有关vector用法的文档将很有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.