在成对列表的向量上迭代
Iterate over a vector of a list of pairs
我试图在一个对列表的向量上迭代,但我一直收到编译错误。我正在为这对中的第一个元素寻找匹配项。
以下是cpp shell上的代码:http://cpp.sh/4ir4p
这是代码:
// Example program
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <utility>
using namespace std;
int main()
{
vector < list < pair <string, string> > > v;
v.resize(15);
string k = "foo";
//want to try and find match
for (size_t i = 0; i < v.size(); i++)
if(v[i].first == k)
cout << "true";
for (const auto & itr : v)
if(itr.first == k)
cout << "true";
cout << "YAY";
}
我一直在两个方法上出错,说我没有首先命名的成员,我不太确定我做错了什么,谢谢你的帮助。
当然,您会遇到编译器错误,std::vector
没有名为first
的成员。当您遍历向量时,迭代器指向一个对列表,您需要进行比较。所以你需要第二个循环:
int main()
{
vector < list < pair <string, string> > > v;
v.resize(15);
string k = "foo";
for (const auto &itList : v)
{
for (const auto &itPair : itList)
{
if (itPair.first == k)
{
cout << "true";
}
}
}
}
您必须为列表引入第二个循环,如:
//want to try and find match
for (size_t i = 0; i < v.size(); i++)
for (auto itr=v[i].begin(); itr != v[i].end(); itr++)
if(itr->first == k)
cout << "true";
在行
vector < list < pair <string, string> > > v;
您定义了一个vector<list<pair>>
,所以后来的v[i]
是一个list
,而不是一对。你不需要一个vector<pair>
吗?
相关文章:
- std::向量迭代器和调整大小/保留的奇怪/有趣行为
- 如何取消引用向量迭代器
- Map中的(字符串的)向量迭代器
- C++将向量迭代器转换为索引
- yaml-cpp到std::向量迭代的怪异行为
- 使用索引与迭代器将向量迭代到倒数第二个元素
- 无法取消引用超出范围的向量迭代器 - 有什么问题?
- 向量迭代器不兼容的错误,用于保存另一个向量的迭代器的向量
- C++向量迭代器nth_element编译错误
- 无法查找值初始化的向量迭代器?
- C++向量迭代:常量 vs. 常量自动 vs. 无常量
- 向量迭代编译为非常不同的指令
- STD ::向量迭代器类型和允许的操作
- 如何通过尺寸未知的2D向量迭代
- 向量迭代器 < 或 !=
- 如何通过共享_ptr向量迭代
- 如何通过向量迭代作为指针
- 通过向量迭代,而其他线程可能会对其进行修改
- 我如何通过C 中的字符串向量迭代
- 向量迭代器在新对象的 push_back() 之后不兼容