Samuel Wibawa
Samuel Wibawa

Reputation: 5

'no known conversion for argument 1 from ‘int’ to ‘const key_type&’ error' when executing code

I'm trying to do an assignment relating to graphs in c++. Currently I get this error when I execute my code. I've been looking around for reasons behind this, but to no avail. Any help will greatly be appreciated. My code snippet is:

 #include <unordered_set> 
 #include <iostream>

 using namespace std;

 map<string,string> all_vertices;
 map<string, map<string, T>> adj_list;     


template <typename T>
size_t Graph<T>::num_edges() {
int edge_num =0;
for (int i =0; i< adj_list.size();i++){      
    for (auto x : adj_list.at(i)){
              edge_num+=1;
      }
} 
return edge_num;

}

The error I get is:

 no known conversion for argument 1 from ‘int’ to ‘const key_type&’ {aka ‘const         std::__cxx11::basic_string<char>&’}
 546 |       at(const key_type& __k) const
     |          ~~~~~~~~~~~~~~~~^~~

Sorry If it is really messy. I'm still very new at this. Any help will be greatly appreciated.

Upvotes: 0

Views: 2288

Answers (1)

Chilippso
Chilippso

Reputation: 491

Explanation

You declare your variable adj_list as type map<string, map<string, T>>.

That is, the map's key is of type string, but you try to access an element of this map via adj_list.at(i), where i (the key) is of type int and not of type string.

There is no implicit conversion of int to string. That's why your compiler is complaining.

Alternative implementation to iterate through the map(s)

template <typename T>
size_t Graph<T>::num_edges() {
    int edge_num = 0;

    for(auto& node : adj_list) {
        for(auto& edge : node.second) {
            edge_num++;
        }
    }

    return edge_num;
}

Upvotes: 3

Related Questions