C + + polymorphism get data merge from different data sources

Source: Internet
Author: User

Define a base class, with pointers to the base class pointing to different subclasses ...


#include <iostream> #include <stdio.h> #include <algorithm> #include <vector>using namespace  Std;class ListNode {public:int val;  Listnode* Next;  ListNode (int x): Val (x), Next (NULL) {}};class DataSource {public:listnode* cur; DataSource (): cur (NULL) {} virtual listnode* getData () = 0;};     Class Disk:public DataSource {public:listnode* getData () {//maybe other implements cur = NULL;   return NULL;     }};class mem:public DataSource {public:listnode* getData () {//maybe other implements cur = NULL;   return NULL; }};class cmp {Public:bool operator () (datasource* A, datasource* b) {return a->cur->val > B->cur->val  ; }};class Solution {Public:listnode *mergeklists (vector<datasource *> &lists) {//note:the Solution obj    ECT is instantiated only once and are reused by each test case.    ListNode *head = null, *cur = NULL;    Vector<datasource*>::iterator it = Lists.begin (); while (it ! = Lists.end ()) {if ((*it)->getdata () = = NULL) it = lists.erase (it);    else it++;    } if (Lists.size () < 1) return NULL;    Make_heap (Lists.begin (), Lists.end (), CMP ());      while (Lists.size () > 0) {if (head = = NULL) head = cur = lists[0]->cur;        else {Cur->next = lists[0]->cur;      Cur = cur->next;                 } pop_heap (Lists.begin (), Lists.end (), CMP ());      if (Lists[lists.size ()-1]->getdata () = NULL) Push_heap (Lists.begin (), Lists.end (), CMP ());          else Lists.pop_back ();  } return head;  }};int Main () {datasource* D1 = new Disk ();  datasource* D2 = new Mem ();  Vector<datasource*> lists;  Lists.push_back (D1);  Lists.push_back (D2);  Solution S;  listnode* res = s.mergeklists (lists); return 0;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.