2011-04-27 2 views
0

구조체의 벡터를 정렬하려고했습니다. 다음 코드는 내 코드입니다. 제대로 정렬 할 수 없습니다 ... 누구든지 나를 도울 수 있습니까? mmNo에 따라 정렬해야합니다. 죄송합니다 ... 나는 코드의 일부를 놓쳤습니다 ...구조를 포함하는 벡터의 정렬

typedef struct MMInfo 
{ 
    std :: string strMmNo; 
    std :: string strMmName; 
    std :: string strMmsPlace; 
    std :: string strMmAdd; 
    std :: string strMmPh; 

    MMInfo(const std::string& mmNo, 
     const std::string& mmName, 
     const std::string& mmPlace, 
     const std::string& mmAdd, 
     const std::string& mmPh) : stringValue(mmNo,),stringValue(mmName), 
            stringValue(mmPlace),stringValue(mmAdd), 
            stringValue(mmPh) {} 

    bool operator < (const MMInfo& str) const 
    { 
    return (mmNo < str.mmNo); 
    } 

} MMInfo; 

std::vector <MMInfo> mmlist; 
MMInfo mmInfo = {"", "", "", "", ""}; 

mmInfo.strMmNo = "3452132"; //actually , i have used a loop to get it from the user 
mmInfo.strMmName="Peter"; 
mmInfo.strMmPlace="TCR"; 
mmInfo.strMmAdd="Street 453"; 
mmInfo.strMmPh="8587556587"; 

mmlist.push_back(mmInfo); 

sort(mmlist.begin(),mmlist.end()); 
for (int i=0; i<mmlist.size(); i++) 
{ 
    cout << " first row :" << mmlist[i].strMmNo << " " << mmlist[i].strMmName 
     <<" " <<mmlist[i].strMmsPlace << " " << mmlist[i].strMmsAdd ; 
} 
+1

왜? "제대로"일어나지 않는 것은 무엇입니까? –

+0

이 코드는 컴파일되지 않습니다. 그것이 왜 컴파일되지 않는가에 대한 질문입니까? –

+1

'mmlist'는 비어 있습니다. 따라서 함께 이동하십시오. 여기서 정렬 할 항목이 없습니다. –

답변

0

코드에는 아무런 문제가 없습니다. 내 말은, 사용법은 맞지만 구조체 정의가 올바르지 않은 것 같습니다. 적어도 Visual C++ 9.0에서는 컴파일 할 수 없습니다. 적절한 초기화 목록을 작성하십시오. 다음 코드는 나를 위해 잘 작동

#include <iostream> 
#include <string> 
#include <vector> 
#include <algorithm> 

using namespace std; 

typedef struct NodeInfo 
{ 
    int x; 

    NodeInfo(int xi){ x = xi; } 
    bool operator < (const NodeInfo& str) const 
    { 
     return (x < str.x); 
    } 
}MMInfo; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    std::vector <MMInfo> mmlist; 

    mmlist.push_back(1); 
    mmlist.push_back(31); 
    mmlist.push_back(21); 
    mmlist.push_back(11); 
    mmlist.push_back(41); 
    sort(mmlist.begin(),mmlist.end()); 
    for (unsigned int i=0; i<mmlist.size(); i++) 
    { 
     cout<< " x row : \n" << mmlist[i].x ; 
    } 
    return 0; 
} 
0

심지어 컴파일합니까? (아니요!)

  • 존재하지 않는 값을 초기화하려고합니다. 어쩌면 stringValue 대신 strMm* 값을 초기화할까요?
  • 여러 번
  • 귀하의 비교 함수는 존재하지 않는 값을 비교 (해당 mm*strMm* 멤버를 초기화) (즉,도 존재하지 않습니다!) 같은 값을 초기화하고 있습니다. (strMmNo < str.strMmNo 비교).

또한 목록에 정렬 ​​할 값도 없습니다.