简体   繁体   中英

Why does pass-in-by-reference cause binding reference type error

When use for-loop , I usually use reference like for(auto& s : words) to avoid temporary copy of each word[i] . But sometime it throws out error.

Could someone please help to clarify when it is ok to use for(auto& s : words) , and when we can ONLY use for(auto s : words) without reference? Any general rule or insight is very much appreciated!

Below is a specific example for illustration. In the main function, we have

    vector<string> topKFrequent(vector<string>& words, int k) {
        vector<string> res;
        if (words.empty()) return res;

        unordered_map<string, int> freq; 
        int max_freq = 0;
        for (auto& word : words) {
            freq[word]++;
            max_freq = max(max_freq, freq[word]);
        }

        // vector<Trie> bucket(max_freq + 1); //Question: if use struct on stack, then how to check whether bucket[i] contains valid words?
        vector<Trie*> bucket(max_freq + 1, NULL); //NOTE: optimization by using max_freq instead of words.size()

        for (auto& kv : freq) {

            Trie*& p_trie = bucket[kv.second]; //NOTE: must use reference &
            if (p_trie == NULL) {
                p_trie = new Trie(); //NOTE: call new Trie(), NOT TrieNode()!!!
            }
            p_trie->addWords(kv.first);
        }
}

In the self-defined class Trie , we have member function

void addWords(string& word) {

   //...omitted
}

addWords(string& word) will throw below error

error: binding reference of type 'std::__cxx11::string&' {aka 'std::__cxx11::basic_string<char>&'} to 'const std::__cxx11::basic_string<char>' discards qualifiers p_trie->addWords(kv.first); ~~~^~~~~,

Why does it say binding string& to const string ?

Short answer

Why does it say binding string& to const string?

Because you (attempt to) do so in the function call to addWords()

Explanation

std::map::value_type is defined as std::pair<const key_type,mapped_type>

Note the const key_type.

Hence, in your code kv.first is const, and you're trying to pass by reference into a non-const function.

You need to do either of the following:

  1. Pass an std::string const&
 void addWords(string const& word) {
     //...omitted
 }
  1. Pass by value (if addWords() needs to modify the local copy)
 void addWords(string word) {
     //...omitted
 }

Sources:

http://www.cplusplus.com/reference/map/map/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM