Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are good alternatives to "using namespace std;"?

I understand that using namespace std; is problematic (e.g. from reading the answers to "Why is using namespace std considered bad practice?").

What are good alternatives to importing the standard namespace like that?

I'd like to know what I can do to improve my code.

like image 335
Ricky Slayer Avatar asked Oct 16 '25 21:10

Ricky Slayer


1 Answers

The main alternatives to bringing in everything from the std namespace into the global one with using namespace std; at global scope are:

  1. Only bring in the actual names you need. For example just bring in vector with using std::vector;

  2. Always use explicit namespace qualifications when you use a name. For example std::vector<int> v; (in headers, this should almost always be the only thing you do)

  3. Bring in all names, but in a reduced scope (like only inside a function). For example void f() { using namespace std; vector<int> v; } - this does not pollute the global namespace.

like image 126
Jesper Juhl Avatar answered Oct 18 '25 12:10

Jesper Juhl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!