遍历地图

Traversing a map

我在这段代码中遇到错误?有人可以告诉原因吗? GFG 上可用的类似代码虽然有效。 附件是代码。 假设头文件 bits/stdc++.hnamespace std.

int main()
{
   int n;
   cin >> n;
   map<ll, vector<int>> val;
   ll arr[n] = { 0 };
   for (int i = 0; i < n; i++)   cin >> arr[i];
   for (int i = 0; i < n; i++)   val[arr[i]].push_back(i);
   for (auto i : val) 
   {
      cout << "Element        Indexes\n";
      cout << val.first << " ----> ";
      for (auto j : val.second)
         cout << j << " ";
      cout << "\n";
   }
   return 0;
}

错误信息

prog.cpp: In function ‘int main()’:
prog.cpp:15:21: error: ‘class std::map<long long int, std::vector<int> >’ has no member named ‘first’
         cout << val.first << " ----> " ;
                     ^
prog.cpp:16:33: error: ‘class std::map<long long int, std::vector<int> >’ has no member named ‘second’
         for(auto const &j : val.second)        
                                 ^

就像错误消息说 val 是类型 std::map<ll, std::vector<int>> 没有第一和第二个成员,而是下划线 std::pair<const ll, std::vector<int>> 有那些。

意思在你的第一个 for 循环中。 (假设 lllong long 的类型别名)

for (auto i : val) // auto = std::pair<const ll, std::vector<int>>

因此你应该

for (const auto& i : val)    // auto = std::pair<const ll, std::vector<int>>

{
    // code
    for (auto j : i.second)  // auto = std::vector<int>
      // code
}

或者如果您使用 , you could use structured binding 更直观

for (const auto&[key, valVector] : val)
//              ^^^^^^^^^^^^^^^^
{
   std::cout << "Element  Indexes\n" << key << " ----> ";
   for (auto j : valVector)
      std::cout << j << "\n";
}

记住,VLAs are not part of standard C++, prefer using std::vector

std::vector<ll> arr(n);