Tyler Kelly
Tyler Kelly

Reputation: 574

Iterate over a vector of a list of pairs

I'm trying to iterate over a vector of a list of pairs and I keep getting compilation errors. I am trying to find a match for the first element of the pair.

Here is the code on cpp shell: http://cpp.sh/4ir4p

and this is the code:

// 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";
}

and I keep getting error for both methods saying I have no member named first, I'm not quite sure what I am doing wrong, thanks for anyhelp.

Upvotes: 1

Views: 5447

Answers (3)

Mauri
Mauri

Reputation: 1245

you must introduce a second loop for the list like:

//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";

Upvotes: 1

vsoftco
vsoftco

Reputation: 56547

In the line

vector < list < pair <string, string> > > v;

you define a vector<list<pair>>, so later v[i] is a list, not a pair. Don't you just need a vector<pair> instead?

Upvotes: 0

Viktor Liehr
Viktor Liehr

Reputation: 538

Of course you are getting compiler errors, std::vector has no member called first. When you iterate through the vector your iterator points to a list of pairs, you want to compare. So you need a second loop:

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";
         }
      }
   }
}

Upvotes: 1

Related Questions