C ++列表迭代器不访问列表的内容

时间:2016-09-17 13:36:16

标签: c++ list stl iterator stdlist

可视化
NTlist :[NTstring,RHSlist]< - > [NTstring,RHSlist]< - > [NTstring,RHSlist] ......

Ntlocation “指向”中间链接 ^ (上图),因为NTstring符合我要搜索的内容。

我想做什么:
使用 NTlocation “指针”我想在这里访问和修改RHSlist。

问题:
Debugger shows RHSlist data being put into NTlocation

But I want RHSlist data to be in element of NTlist

非常感谢您的协助!

EDIT。每个请求添加代码。再次感谢!

typedef struct RHSnode {
  token_type type;
  string token;
} RHSnode;

typedef struct NTnode {
  token_type type;
  string token;
  list<RHSnode> RHSlist;
} NTnode;

int function {
  list<NTnode> NTlist;
  list<NTnode>::iterator NTlocation;

  freopen("example.txt", "r", stdin);
  t_type = getToken(); //this function gets tokens from txt file above
  // code has been simplified for your viewing pleasure
  // but basically NT.list is created for each token listed at start of 
  // text file in the following manner.  (This works fine)
  NTnode entry;
  entry.token = string(current_token);
  NTlist.push_back(entry);
  t_type = getToken();

  // loop until all tokens are read 
  {
    t_type = getToken(); 
    string NTstring = string(current_token);
    NTlocation = searchNTList(NTstring, NTlist);

    RHSnode entry;
    entry.token = string(current_token);

    //****Here is the problem:
    NTlocation->RHSlist.push_back(entry);            

  }

  return 1;
}

list<NTnode>::iterator searchNTList(string NTstring, list<NTnode> &NTlist){
  list<NTnode>::iterator NTlocation = NTlist.end(); //"past-the-end"     indications search failure
  list<NTnode>::iterator iterator = NTlist.begin();

  for ( ; iterator != NTlist.end() ; iterator++ ){

    if (iterator->token.compare(NTstring) == 0){
      NTlocation = iterator;
      break; 
    }

  }
  return NTlocation;
}

1 个答案:

答案 0 :(得分:1)

至少:

list<NTnode>::iterator searchNTList(string NTstring, list<NTnode> NTlist){

这会将迭代器返回到NTlist的本地副本。您可能希望通过const引用传递NTlist