在成对列表的向量上迭代

Iterate over a vector of a list of pairs

本文关键字:向量 迭代 列表      更新时间:2023-10-16

我试图在一个对列表的向量上迭代,但我一直收到编译错误。我正在为这对中的第一个元素寻找匹配项。

以下是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>吗?