I was trying to sort a vector of struct.The following is my code.I am not able to sort it properly...Can anyone help me..?I need to sort according to the mmNo.Sorry ...i missed some part of the code...
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";
mmInf开发者_StackOverflow中文版o.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 ;
}
Your code has no problems. I mean, the usage is right but the structure definition seems not correct. It's not compilable at least in Visual C++ 9.0 Please make a proper initialization list. The following code worked fine for me
#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;
}
Does that even compile? (No!)
- You're trying to initialize values that don't exist. Maybe initialize your
strMm*
values instead ofstringValue
? - You're initializing the same value (that doesn't even exist!) multiple times (Initialize
strMm*
members with a correspondingmm*
value) - Your comparison function compares values that don't exist. (Compare
strMmNo < str.strMmNo
).
Also, you don't even have values to sort in your list.
精彩评论