为什么按引用传入会导致绑定引用类型错误

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

本文关键字:绑定 引用类型 错误 引用 为什么      更新时间:2023-10-16

当使用for-loop时,我通常使用像for(auto& s : words)这样的引用来避免每个word[i]的临时副本。但有时它会抛出错误。

有人可以帮忙澄清什么时候可以使用for(auto& s : words),什么时候我们只能在没有参考的情况下使用for(auto s : words)?任何一般规则或见解都非常感谢!

下面是一个具体示例进行说明。在主函数中,我们有

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);
}
}

在自定义class Trie中,我们有成员函数

void addWords(string& word) {
//...omitted
}

addWords(string& word)将抛出以下错误

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); ~~~^~~~~,

为什么说string&绑定const string

简答

为什么说绑定字符串和常量字符串?

因为你(尝试(在函数调用addWords((中这样做

解释

std::map::value_type定义为std::pair<const key_type,mapped_type>

请注意常量key_type。

因此,在您的代码中,kv.first是 const,并且您尝试通过引用传递到非 const 函数中。

您需要执行以下任一操作:

  1. 传递std::string const&
void addWords(string const& word) {
//...omitted
}
  1. 按值传递(如果addWords((需要修改本地副本(
void addWords(string word) {
//...omitted
}

来源:

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

相关文章: