[英]looping through a vector of iterators with an iterator
I get an error in the final for loop:我在最后的 for 循环中得到一个错误:
error: conversion from '__normal_iterator<__gnu_cxx::__normal_iterator<int*, std::vector<int> >*,vector<__gnu_cxx::__normal_iterator<int*, std::vector<int> >>>' to non-scalar type '__normal_iterator<const int*,vector<int>>' requested
20 | for(vector<int>::const_iterator t=ind.begin(); t != ind.end(); ++t){
| ~~~~~~~~~^~
I kept looking for solutions to similar problems and I still don't get what I did wrong.我一直在寻找类似问题的解决方案,但我仍然不明白我做错了什么。
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,m,a;
vector<int>::iterator b;
cin>>n>>m;
vector<int> seq(n);
vector<vector<int>::iterator> ind;
for(int i=0;i<n;i++){
cin>>seq[i];
}
for(int i=0;i<m;i++){
cin>>a;
b=find(seq.begin(),seq.end(),a);
if(b!=seq.end()){
ind.push_back(b);
}
}
sort(ind.begin(),ind.end());
for(vector<int>::const_iterator t=ind.begin(); t != ind.end(); ++t){
cout<<*t;
}
return 0;
}
vector<int>::const_iterator
is an iterator for a vector
of int
. vector<int>::const_iterator
是int
vector
的迭代器。 An iterator for a vector of iterators is vector<vector<int>::iterator>::const_iterator
.迭代器向量的迭代器是
vector<vector<int>::iterator>::const_iterator
。
To avoid typing such monster types, use auto
:为避免输入此类怪物类型,请使用
auto
:
for(auto t=ind.begin(); t != ind.end(); ++t){
cout<<*t;
}
or when you iterate from begin till end, a range based loop:或者当您从开始到结束迭代时,基于范围的循环:
for(auto t : ind){
cout<<t;
}
As you didnt include the error (at the time of writing this) I fixed only the obvious error.由于您没有包含错误(在撰写本文时),我只修复了明显的错误。 I suppose you need to dereference the iterator to print the actual element (ie add a
*
in both examples above).我想您需要取消引用迭代器以打印实际元素(即在上面的两个示例中添加
*
)。
The vector ind
is a vector of elements of the type std::vector<int>::iterator
.向量
ind
是std::vector<int>::iterator
类型元素的std::vector<int>::iterator
。
So in the for loop you have to write at least like所以在 for 循环中你必须至少写
vector<vector<int>::iterator>::const_iterator t=ind.begin();
And it seems within the loop you mean它似乎在你的意思的循环中
cout<<**t;
instead of代替
cout<<*t;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.