使用迭代器C++的嵌套循环

Nested loop using iterator C++

本文关键字:嵌套循环 C++ 迭代器      更新时间:2023-10-16

陷入非常有趣的问题。

您之前可能在 C/C++ 中执行此操作

map<string, string> dict;
dsz = dict.size();
vector<string> words;
int sz = words.size();
for(int i = 0; i < sz; ++i)
{
   for(int j = i + 1; j < dsz; ++j)
   {
   }
}

我将如何使用迭代器实现同样的事情。

请指教。

好的。我想通了。更准确地说,我希望 i 和 j 都在内部循环中。

在这里我用迭代器做了,抱歉,由于需求的变化,我必须移动到多映射而不是地图。

vector<string>::iterator vit;
multimap<string, string>::iterator top = dict.begin();
multimap<string, string>::iterator mit;
for(vit = words.begin(); vit != words.end(); ++vit)
{
  string s = *vit;
  ++top;
  mit = top;
  for(; mit != dict.end(); ++mit)
  {
    /* compare the value with other val in dictionary, if found, print their keys */
    if(dict.find(s)->second == mit->second)
      cout << s <<" = "<< mit->first << endl;
  }
}

任何其他有效的方法来做到这一点都将不胜感激。

你的最终意图并不完全清楚,因为你在 i+1 上启动了 j 循环(见最后的注释(。 在你澄清这种关系之前,我向你提出两个临时解决方案

方法1:简单而优雅:

您可以使用新的基于 C++11 范围的 for((。 它使用了一个从 begin(( 开始到 end(( 的迭代器,而不必为此迭代器而烦恼:

for (auto x : words)  {    // loop on word  (size sz) 
    for (auto y : dict) {  // loop on dict (size dsz)
        // do something with x and y, for example: 
        if (x==y.first)
            cout << "word " << x << " matches dictionary entry " << y.second << endl;
    }
}

方法2:迭代器的传统使用

您还可以显式指定要使用的迭代器。 与前面的示例相比,这有点冗长,但它允许您选择最合适的迭代器,例如,如果您想要像 cbegin(( 而不是 begin(( 这样的常量迭代器,如果您想跳过一些元素或在迭代器上使用改编器,suc 例如 reverse_iterator,等等:

for (auto itw = words.begin(); itw != words.end(); itw++) {
    for (auto itd = dict.begin(); itd != dict.end(); itd++) {
        // do simething with *itw and *itd, for example: 
        if (*itw == itd->first)
            cout << "word " << *itw << " matches dictionary entry " << itd->second << endl;
    }
}

言论:

仅当向量的元素与映射中的元素相关时word以 j=i+1 开始 intter 循环才有意义dict(好吧,它们也是 cerainly 单词(,并且您在映射中访问的元素顺序与向量中的顺序相关。由于映射是根据键排序的,因此只有单词也会按照相同的键进行排序。是这样吗?

如果您仍然想跳过元素或根据元素之间的距离进行计算,您宁愿考虑上面提出的第二种方法。 它使使用distance(itw, words.begin())变得更容易,这相当于 i。

但是,最好使用利用其设计的包含器。 因此,与其通过字典映射进行迭代以查找单词条目,不如按如下方式使用映射:

for (auto x : words)  {    // loop on word  (size sz) 
    if (dict.count(x))    // if x is in dictionary 
        cout << "word " << x << " matches dictionary entry " << dict[x] << endl;
}