使用迭代器C++的嵌套循环
Nested loop using iterator C++
陷入非常有趣的问题。
您之前可能在 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;
}
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 了解嵌套循环打印星号图案
- 无法掌握嵌套循环的写作技巧
- 在 c++ 中实现嵌套循环的更短方法吗?
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 毕达哥拉斯三重嵌套循环误解
- T(n) 表示嵌套循环
- 2 个嵌套循环的时间复杂度
- 嵌套循环背后的逻辑
- 使用 %s C++嵌套循环
- 嵌套循环和重复迭代器
- 如何在 c++ 下使用嵌套循环和正则表达式降低时间复杂度?
- C++在乘法图中放置随机值(嵌套循环)
- 如何使用 OpenMP 减少嵌套循环?
- 为什么使用 2 个嵌套循环 O(n^2) 复杂度来解决二和问题,当只改变循环计数器逻辑时运行得更快?
- 学习嵌套循环C++与示例混淆
- 如何在CUDA中嵌套循环
- std::vector上的嵌套循环
- 具有动态数组分配的OpenMP嵌套循环
- 两个嵌套循环的运行时间复杂性:二次型还是线性