迭代对列表的向量

时间:2015-11-27 19:21:24

标签: c++ list vector iterator std-pair

我试图迭代一对列表的向量,并且我不断收到编译错误。我试图找到该对的第一个元素的匹配。

以下是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";
}

并且我继续收到两种方法的错误,说我没有先命名的成员,我不太确定我做错了什么,谢谢你的帮助。

3 个答案:

答案 0 :(得分:1)

当然,您收到了编译错误,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";
         }
      }
   }
}

答案 1 :(得分:1)

你必须为列表引入第二个循环,如:

<select id="id_dystrybutor_glowny">
<option value="1">Dyst1</option>
<option value="2">Dyst2</option>
<option value="3">Dyst3</option>
</select>
<input type="checkbox" class="dystrybutor" value="1"> Dyst1<br/>
<input type="checkbox" class="dystrybutor" value="2"> Dyst2<br/>
<input type="checkbox" class="dystrybutor" value="3"> Dyst3<br/>
<script>
$(document).ready(function () {
$('#id_dystrybutor_glowny').change(function () {
    var dID = $(this).find(":selected").val();         
    if $('.dystrybutor').attr( "value" ) == dID {
        $(this).prop('checked', true);
    };
  });     
});
</script>

答案 2 :(得分:0)

在第

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

您定义了vector<list<pair>>,因此稍后v[i]list,而不是一对。你不只需要一个vector<pair>吗?

相关问题