Is writing "std::" before stoi(s.substr(2,3)) mandatory?

Viewed 150

I have seen that even if you don't add std:: before stoi(s.substr(3,4)) (where s="123456789") it works fine, and also if you write std::stoi(s.substr(3,4)) the result is the same. So, is writing it like std::stoi(s.substr(3,4)) mandatory, or is it just good practice?

std::string s = "123456789";
int ans = stoi(s.substr(3,4));
std::cout<<ans;
std::string s = "123456789";
int ans = std::stoi(s.substr(3,4));
std::cout<<ans;

Both gives the same answer. And also sometimes writing std::stoi(s.substr(3,4)); gives an error.

4 Answers

It compiles without std:: because of the argument-dependent lookup.

I say it's a good practice to use std::stoi because:

  • It's more obvious that a standard function is being called.
  • It will not break if someone defines a variable named stoi prior to your code. This can be fixed by adding using std::stoi;, but since you call it once, it's more verbose than calling std::stoi directly.

It is considered good practice to add std:: namespace, so you can avoid conflicts if you use different libraries etc. The probable reason it gives you an error sometimes is because you probably don't include the string header of the standard library:

#include <string>

but it is difficult without seeing the error, so please provide the details

Likely, if you can use stoi and get the same result as std::stoi, you might be using namespace std already.

This is not always desirable, depending on the project philosophy and the rest of your code suggests that you shouldn't depend on it.

edit: in this case, OP does not use using namespace std and something more subtle is going on (thanks @HolyBlackCat).

stoi() exists in the std namespace, so using stoi() without std:: works if there is a preceding using namespace std; or using std::stoi; statement, or when passing in a std::string object as an argument value due to Argument-Dependent Lookup (since string and stoi() are in the same namespace).

Related