What is the Best Way to Use Namespaces in C++?

  • Context: Comp Sci 
  • Thread starter Thread starter Linda8888
  • Start date Start date
  • Tags Tags
    C++
Click For Summary

Discussion Overview

The discussion revolves around the use of namespaces in C++, specifically focusing on the implementation and implications of using "using namespace std;" and type aliases for iterators. The scope includes technical explanations and code examples.

Discussion Character

  • Technical explanation

Main Points Raised

  • One participant provides a code snippet using "using namespace std;" and defines a type alias for a vector string iterator, suggesting it simplifies code by reducing repetitive typing.
  • Another participant offers a similar code snippet but modifies the function parameter to take a non-const reference to the vector, which may imply a different intended usage.
  • A third participant acknowledges a correction made to the original post, indicating collaborative refinement of the code shared in the thread.

Areas of Agreement / Disagreement

Participants appear to agree on the utility of type aliases for simplifying code, but there are variations in the implementation details, particularly regarding the function parameter type. The discussion does not reach a consensus on the best practice for using namespaces.

Contextual Notes

There are unresolved aspects regarding the implications of using "using namespace std;" in larger projects, as well as the potential impact of passing vectors by reference versus by const reference.

Linda8888
Messages
7
Reaction score
1
Homework Statement
Explain what is wrong with the following code fragment(other than missing #include) and write down the change(s) that you will make to fix the problem(s).
Relevant Equations
I'm not sure what does "using" means at the second but I guess it is wrong.
C++:
using namespace std;
using vit = vector<string>::iterator;
void print(const vector<string>& s) {
  for(vit it = s.begin(); it != s.end(); ++it ) {
    count << *it << endl;
  }
}
 
Last edited by a moderator:
Physics news on Phys.org
It’s an abbreviation for the vector string iterator data type. It primarily saves the programmer from typing it over and over.
 
  • Like
Likes   Reactions: Linda8888
C++:
using namespace std;
using vit = vector<string>::iterator;
void print(vector<string>& s) {
  for(vit it = s.begin(); it != s.end(); ++it ) {
    count << *it << endl;
  }
}
 
  • Like
Likes   Reactions: Curtisc, jedishrfu and berkeman

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 24 ·
Replies
24
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 23 ·
Replies
23
Views
9K
  • · Replies 7 ·
Replies
7
Views
2K