为什么按引用传入会导致绑定引用类型错误
Why does pass-in-by-reference cause binding reference type error
当使用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 函数中。
您需要执行以下任一操作:
- 传递
std::string const&
void addWords(string const& word) {
//...omitted
}
- 按值传递(如果addWords((需要修改本地副本(
void addWords(string word) {
//...omitted
}
来源:
http://www.cplusplus.com/reference/map/map/
相关文章:
- 运行时错误:引用绑定到类型为"int"的空指针
- 运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebebebec6,这需要 4 个字节对齐 (stl_vector.h)
- 无法将类型"T&"的非常量左值引用绑定到类型"T"的右值 t++ std::atomic<T>
- 在其他容器中使用 boost::container::static_vector 时,GCC 编译错误"将'const s'绑定到类型's&'的引用丢弃限定符"
- 为什么定义复制构造函数会给我错误:无法将类型 'obj&' 的非常量左值引用绑定到类型为"obj"的右值?
- 错误:对类型 'const ItemInstance' 的引用无法绑定到类型 'void' 的右值
- 错误:在类型 "blah blah" 的绑定引用中删除限定符以初始化"some other blah blah"
- 为什么按引用传入会导致绑定引用类型错误
- 对类型的非常量左值引用无法绑定到类型为"*"的临时
- 错误:绑定到类型引用会丢弃限定符
- 对类型"项 *const"的引用无法绑定到类型为"const 项 *"的右值
- 无法将类型为"类名 &"的非常量左值引用绑定到类型为"类名"的右值
- 将引用绑定到类型的值会删除限定符 MULTISET
- 错误:将"const double"绑定到类型为"double&"的引用会丢弃限定符
- 无法将类型"int&"的非常量左值引用绑定到类型为"int"的右值
- 不能将类型的非常量左值引用绑定到类型的右值
- 错误:无法将类型为"int&"的非常量左值引用绑定到类型为"int"的右值
- 来自std::tuple的引用绑定的类型
- 引用绑定到类型 'struct value_type' 的 null 指针
- 将引用绑定到类型值会删除限定符