vector는 동적배열 처리할때 매우 유용합니다.
이걸 특정 키로 sort 할려다가 생각이 않나 자료를 찾아 보고
예제를 올립니다. 머.. 예제 같지도 않은 것이지만... 혹 쓰려는 분에게 도움이 될지도 모른다는 생각에 ㅡ..ㅡ;
폼에는 버턴 하나, 메모장 하나 올려 놓으시면 됩니다.
sort 를 위한 < 연산자 오버로딩시 함수 프로토타입을 예제와 같이 맞춰주는 것에 유의하시면 됩니다.
// pvectorlist.cpp
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <vector>
#include <algorithm>
#include "pvectorlist.h"
using namespace std;
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
class TA
{
public:
~TA()
{
int k = 0;
}
};
struct TCard
{
public:
int No;
char Name[100];
int Age;
String Part;
TA ta;
// sort() 를 위한 오버로딩
bool operator<(const TCard& a) const
{
return strcmp(Name, a.Name) < 0;
}
};
/* 이런식으로 클래스외부에서 sort를 위한 < 연산자 오버로딩을 해도 된다.
bool operator<(const TCard& a, const TCard& b)
{
return strcmp(a.Name, b.Name) < 0;
}
*/
void __fastcall TForm1::Button1Click(TObject *Sender)
{
vector<TCard> list(2);
TCard a;
String str = "haha";
strcpy(a.Name, "Kim3");
a.Part = "haha 1";
list[0] = a;
list.push_back(a);
strcpy(a.Name, "Lee");
a.Part = "haha 2";
list.push_back(a);
strcpy(a.Name, "Kim2");
a.Part = "haha 3";
list.push_back(a);
strcpy(a.Name, "Choi");
a.Part = "haha 4";
list.push_back(a);
list[1] = a;
for(vector<TCard>::iterator it = list.begin(); it != list.end(); it++)
{
Memo1->Lines->Add(it->Part + " " + it->Name);
}
Memo1->Lines->Add("");
list.erase(&list[0]);
list.erase(&list[0]);
for(UINT c = 0; c < list.size(); c++)
{
Memo1->Lines->Add(list[c].Part + " " + list[c].Name);
}
Memo1->Lines->Add("");
if (list[0] < list[1])
Memo1->Lines->Add("ok");
sort(list.begin(), list.end());
for(UINT c = 0; c < list.size(); c++)
{
Memo1->Lines->Add(list[c].Part + " " + list[c].Name);
}
}
//---------------------------------------------------------------------------
/*
template<typename C> void dump(const char *desc, C c)
{
cout.width(12);
cout << left << desc << "==> ";
copy(c.begin(), c.end(), ostream_iterator<typename C::value_type>(cout," "));
cout << endl;
}
*/
결과는
Memo1
haha 1 Kim3
haha 4 Choi
haha 1 Kim3
haha 2 Lee
haha 3 Kim2
haha 4 Choi
haha 1 Kim3
haha 2 Lee
haha 3 Kim2
haha 4 Choi
ok
haha 4 Choi
haha 3 Kim2
haha 1 Kim3
haha 2 Lee
이렇게 나옵니다.
|
자바의 자료구조가 마음에 들었던 적이 있는데 STL의 vector나 list를 사용한 후로는 비슷하네요.
예제 감사합니다.