Hi, everyone I meet some problem when I try to use the sort algo in STL to sort a structure that contains pointers. I am sure I have define the proper copy constructor to avoid memory disorder. However, it seems that the sort function disorder the memory. Could you give some advice on it? The following is the test code: #include #include #include #include #include #include #include using namespace std; struct str_info { string content; size_t occ_sum; long * occ_pos; // occurrence public: str_info(): content(""), occ_sum(0),occ_pos(NULL){} ~str_info() { if (occ_pos != NULL) delete[] occ_pos; occ_pos = NULL; } str_info(const str_info& info){ content = info.content; occ_sum = info.occ_sum; occ_pos = new long[occ_sum+1]; memcpy(occ_pos, info.occ_pos, sizeof(long)*occ_sum); } }; class cmp_str_info { public : int operator()(const str_info& info1, const str_info& info2) const { return strcmp(info1.content.c_str(), info2.content.c_str()) < 0; } }; void init(str_info * info) { info[0].content = "info0"; info[0].occ_sum = 1; info[0].occ_pos = new long[info[0].occ_sum]; info[0].occ_pos[0] = 45; info[1].content = "a_info1"; info[1].occ_sum = 1; info[1].occ_pos = new long[info[1].occ_sum]; info[1].occ_pos[0] = 55; info[2].content = "b_info2"; info[2].occ_sum = 1; info[2].occ_pos = new long[info[2].occ_sum]; info[2].occ_pos[0] = 35; } int main() { vector vstr; vstr.clear(); str_info info[3]; init(info); vstr.push_back(info[0]); vstr.push_back(info[1]); vstr.push_back(info[2]); vector::iterator it; cout<<"Before sorting....\n"; for (it = vstr.begin(); it != vstr.end(); it++) { cout<content<<" "<occ_pos[0]<content<<" "<occ_pos[0]<
Y
Yu Yang
@Yu Yang