Search code examples
c++c++14traversalstdmapstd

Traversing a map


I am getting an error in this code? Can someone tell the reason? A similar code available on GFG works although. Attached is the code. assume the header file bits/stdc++.h and namespace 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;
}

Error message

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)        
                                 ^

Solution

  • Like the error message says val is type of std::map<ll, std::vector<int>> has no first and second member, rather the underlining std::pair<const ll, std::vector<int>> has those.

    Meaning in your first for loop. (assuming that the ll is a type alias for long long)

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

    therefor you should have

    for (const auto& i : val)    // auto = std::pair<const ll, std::vector<int>>
    
    {
        // code
        for (auto j : i.second)  // auto = std::vector<int>
          // code
    }
    

    Or if you are using , you could use structured binding for more intuitive

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

    Remember, VLAs are not part of standard C++, prefer using std::vector instead.

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