问一个C++ set和unordered_set iterator的问题# JobHunting - 待字闺中
e*s
1 楼
以下这段代码 把set的iterator直接传递到parameter为reference的函数里
报错
test.cpp: In function 'int main()':
test.cpp:110: error: invalid initialization of reference of type 'std::
string&' from expression of type 'const std::basic_string traits, std::allocator >'
test.cpp:67: error: in passing argument 1 of 'void foo(std::string&)'
make: *** [a] Error 1
如果修改代码
1. void foo(string &s) --> void foo(string s)
2. string s = *it; foo(s);
3. void foo(string &s) --> void foo(const string &s)
4. unordered_set vs --> vector vs;
都不会报错.
原因是什么呢, 1. 2.可以理解为dereference不能传入reference parameter中去,因
为可能会引用局部变量
3. 可以理解为不能修改set::iterator指向都局部变量
4. 就很奇葩了, vector::iterator 和 set::iterator的区别不应该在dereference上把
在标准上好像就是random access iterator 和 bidirectional iterator的区别
编译器是 gcc 4.4.2
void foo(string &s)
{
return;
}
unordered_set vs;
for(auto it = vs.begin(); it != vs.end(); ++it){
foo(*it);
}
报错
test.cpp: In function 'int main()':
test.cpp:110: error: invalid initialization of reference of type 'std::
string&' from expression of type 'const std::basic_string
test.cpp:67: error: in passing argument 1 of 'void foo(std::string&)'
make: *** [a] Error 1
如果修改代码
1. void foo(string &s) --> void foo(string s)
2. string s = *it; foo(s);
3. void foo(string &s) --> void foo(const string &s)
4. unordered_set
都不会报错.
原因是什么呢, 1. 2.可以理解为dereference不能传入reference parameter中去,因
为可能会引用局部变量
3. 可以理解为不能修改set::iterator指向都局部变量
4. 就很奇葩了, vector::iterator 和 set::iterator的区别不应该在dereference上把
在标准上好像就是random access iterator 和 bidirectional iterator的区别
编译器是 gcc 4.4.2
void foo(string &s)
{
return;
}
unordered_set
for(auto it = vs.begin(); it != vs.end(); ++it){
foo(*it);
}