I have the following code, which works fine, however when I change the iter getB(string& s , string& tag); function definition to iter getB(const string& s , const string& tag); I get the error pasted at the end. I believe the = operator is not defined because with this new function definition, if I don’t assign the result of search to i the program compiles, though later resulting in a segmentation fault, which I believe is expected. Can someone explain to me why I can’t assign the result of search when the function definition contains const keywords. Thank you.
the code:
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
typedef string::iterator iter;
iter getB(string& s , string& tag);
int main (){
string line = "hello, how are you?";
string tag = "how";
iter i = getB(line,tag);
for(i ; i!=line.end(); i++){
cout << *i ;
}
cout << endl;
return 0;
}
iter getB(string& s , string& tag)
{
iter i;
i = search(s.begin() , s.end() , tag.begin() , tag.end());
return i;
}
~
~
the error message with the altered function definition:
test1.cpp: In function ‘iter getB(const std::string&, const std::string&)’:
test1.cpp:24: error: no match for ‘operator=’ in ‘i = std::search [with _ForwardIterator1 = __gnu_cxx::__normal_iterator<const char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, _ForwardIterator2 = __gnu_cxx::__normal_iterator<const char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >](((const std::string*)s)->std::basic_string<_CharT, _Traits, _Alloc>::begin [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>](), ((const std::string*)s)->std::basic_string<_CharT, _Traits, _Alloc>::end [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>](), ((const std::string*)tag)->std::basic_string<_CharT, _Traits, _Alloc>::begin [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>](), ((const std::string*)tag)->std::basic_string<_CharT, _Traits, _Alloc>::end [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]())’
/usr/include/c++/4.2.1/bits/stl_iterator.h:637: note: candidates are: __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >& __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::operator=(const __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >&)
If
sis aconst string &, thens.begin(), and hence the return type ofsearch, isstring::const_iterator. This is not convertible tostring::iterator, which is the type ofi.This is as it should be, since otherwise that conversion would break
const-correctness by allowing you to modify the string. You should change the type ofitostring::const_iterator, or perhapsautoif you’re using C++11.