-2

I was following a hash table implementation tutorial and came across this:

class HashTable {
private:
    static const int hashGroups = 10;
    std::list<std::pair<int,std::string>> table[hashGroups];

bool HashTable::isEmpty() const {
    int sum{};
    for(int i{}; i < hashGroups; i++) {
        sum += table[i].size();
    }
    
    if(!sum) {
        return true;
    }
    return false;
}

In the isEmpty() member function, why is table[i].size() valid? In my interpretation, table is a list of pairs, therefore, table[i] should return a pair at index [i]. However, there are no member function size() in std::pair.

  • It's easy enough to focus on `std::list>` - that's a scary lot of punctuation for someone learning the language, but another point where you might have realised what you'd done was when you thought *"`table[i]` should return a pair at `index [i]`"* - because list data structures aren't randomly indexable, the Standard Library doesn't provide an `operator[](size_t)` member for `std::list` - that would almost be encouraging beginners to write horribly inefficient code. A good place to check such things is https://en.cppreference.com/w/cpp/container/list – Tony Delroy Jun 19 '21 at 16:34

1 Answers1

8

table is an array of std::list of std::pair, so table[i] is a std::list and it has size() function.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70