2016-11-09 92 views
0

我创建了一个数据包结构。我读了一个文件的文本并转换为字典顺序。为了做到这一点,我必须将两个字符串转换为小写字母来比较它们(一个用于当前节点,另一个用于它旁边的节点)。但是我的问题是当我有大的文本文件时,它必须不断将字符串转换为小写字母,以便插入每个节点,并且有时需要很长时间才能处理。我想知道是否有更好的方法来调整这个方法,这样我就可以提高性能。调试大文本文件花费太多时间

void insert(string v) 
{ 
if(head == NULL){ //empty list 

     head = new BagNode; 
     head->dataValue = v; 
     //head->dataCount = 0; 
     head->next = NULL; 

} 
else 
{ 
     BagNode * n = new BagNode;  // new node 
     n->dataValue = v; 
     BagNode * current = head;   //for traversal 
     //current = head; 
     n->dataCount = 0; 
      if(!isBefore(current->dataValue, v))  //new head 
      { 
       n->next = head; 
       head = n; 
      } 
      else{   //mid and tail insert 
       while(current->next && isBefore(current->next->dataValue,v)) 
       { 
        current = current->next; 
       } 
       n->next = current->next; 
       current->next = n; 

      } 
    }  
} 

比较两个节点

bool isBefore(string a, string b) 
{ 
    transform(a.begin(), a.end(), a.begin(), ::tolower); 
    transform(b.begin(), b.end(), b.begin(), ::tolower); 
    if(a == b) { 
     return true; 
    } 
    else { 
     return false; 
    } 
} 
+0

你使用链表吗?当列表变大时,如果您不断遍历整个列表中的每个新条目,那么这会让您的O(可怕)性能下降。 – Robert

+0

我发现你的标题混乱。什么时间花费太长时间,在大文件上运行程序或实际调试它? – Robert

+0

要开始,我会将'datavalue'保存为小写字符串。这样你只会将事情小写一次。 – Matt

回答

0

我将消除重复调用transform这样的:

void insert(string v) 
{ 
transform(v.begin(), v.end(), v.end(), ::tolower); 
if(head == NULL){ //empty list 

     head = new BagNode; 
     head->dataValue = v; 
     //head->dataCount = 0; 
     head->next = NULL; 

} 
else 
{ 
     BagNode * n = new BagNode;  // new node 
     n->dataValue = v; 
     BagNode * current = head;   //for traversal 
     //current = head; 
     n->dataCount = 0; 
      if(!isBefore(current->dataValue, v))  //new head 
      { 
       n->next = head; 
       head = n; 
      } 
      else{   //mid and tail insert 
       while(current->next && isBefore(current->next->dataValue,v)) 
        { 
         current = current->next; 
        } 
        n->next = current->next; 
        current->next = n; 

       } 
     }  
    } 

bool isBefore(string a, string b) 
{ 
    if(a == b) { 
     return true; 
    } 
    else { 
     return false; 
    } 
} 

你可以看到变换here一些附加信息。这个转变的建议是循环你的范围。找到这样的东西的方法将在GCC上用-pg标志进行编译。这将启用配置文件,并且您将看到具有isBeforetransform功能的热点。