【问题标题】:trouble working with map iterators in c++在 C++ 中使用映射迭代器时遇到问题
【发布时间】:2016-04-01 09:30:37
【问题描述】:

我正在尝试浏览我的患者 ID 地图,找到匹配的连续 ID,并找到每对结果的差异平方(对于同一患者)。但是,我在“for (itid = nx; itid != mymap.end(); itid++) {” 行中的“itid”迭代器遇到了一些问题,我不知道为什么。当我用“itid”取出代码时,它工作得很好。我是一个编程初学者,所以任何建议将不胜感激!

map <int,struct testInfo> mymap;
map <int,struct testInfo>:: iterator it;
pair<map<int,struct testInfo>::iterator,bool> ret;
map <int,struct testInfo>:: iterator itid;



    int arraySize = 10000;
    double diffsq[arraySize];
    int count = 1;

    for ( it=mymap.begin() ; it != mymap.end(); it++ ) {

        auto nx = next(it);

        //comparing each patientID to the next patientID
        if ((it->second.patientID == nx->second.patientID) && it->second.patientID != 0) {

            for (itid = nx; itid != mymap.end(); itid++) {

                if ((it->second.patientID == itid->second.patientID) && it->second.patientID != 0) {

                    diffsq[count] = pow((it->second.result - itid->second.result), 2); 
                    count++;

                } else
                    itid = mymap.end();

            }

        }

    }

【问题讨论】:

  • nx初始化后,nx可能是结束迭代器,但你不去检查。
  • int 在 map 中代表什么?
  • 我怀疑“一些麻烦”是由itid = mymap.end(); 引起的(与以下itid++ 的组合不好)。为什么这条线存在?
  • 嗨 molbdnilo,非常感谢!我认为我的意图是摆脱“for”循环……但显然我没有考虑清楚。我把它改成了 else break;
  • 指定“一些麻烦”。

标签: c++ dictionary iterator


【解决方案1】:

我认为这是因为 next 提供了一个常量迭代器,而 itid 不是 constant... 以与 auto nx 相同的方式尝试 itid。 auto itid = nx 在 for 循环中。

【讨论】:

  • 嗨 Ajay,我实际上先尝试了 auto itid = nx,但它给了我一个错误,这就是我更改它的原因
  • @aspn 目前的问题是运行时间吗?以及您在使用 auto itid = nx 时遇到了什么错误?
  • Ajay @Bob__ 原来问题是没有检查“nx”作为结束迭代器。我将其改回“auto itid = nx”,但据我所知,两种方式现在都可以在“nx”部分更正后运行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 2021-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 2011-07-31
相关资源
最近更新 更多