This is my function, I have run with -std=c++17 -Wall -Wextra
with clang
and gcc
on godbolt
;
both compilers did not produced any errors;
function returns 0
, when empty needle; returns -1
when needle not found and returns index
of first occurrence when match.
int strStr(string haystack, string needle) {
if ( needle.empty( ) ) return 0;
std::size_t n_len = needle.size();
if( needle.size() > haystack.size() ) return -1;
int index = 0;
for ( auto it = haystack.begin(); it != haystack.end(); ++it )
{
std::cout << std::string( it, it + n_len ) << std::endl;
if ( std::string( it, it + n_len ) == needle ) return index; // hear also
//if ( !*(it + n_len ) ) break;
index++;
}
return -1;
}
I know I can get the results using find
or substr
;
I have tested with below, it should produce error, when I access out of bound, but no errors;
int main()
{
std::cout << strStr( "aabaaaababaababaa", "bbbb") << std::endl; // prints -1
std::cout << strStr( "hello", "ll") << std::endl; // prints 2
std::cout << strStr( "mississippi", "issip") << std::endl; // prints 4
std::cout << strStr( "ab", "a") << std::endl; // prints 0
}
Thank you for your time and assistance;
it should produce error, when I access out of bound
No.
The behaviour of accessing an array out of bounds is undefined. There is no guarantee that you would get an error.
but I have tested same code leetcode platform, it produced runtime error
There is also no guarantee that you would not get an error. There are no guarantees whatsoever.