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

  • Thread starter Thread starter Linda8888
  • Start date Start date
  • Tags Tags
    C++
AI Thread Summary
The discussion focuses on the use of namespaces in C++, specifically the convenience of using "using namespace std;" and type aliases like "using vit = vector<string>::iterator." This approach simplifies code by reducing repetitive typing of complex types. The provided code examples demonstrate how to implement a print function for a vector of strings using an iterator. The conversation also includes a mention of editing the original post for clarity. Overall, the thread emphasizes the benefits of using namespaces and type aliases for cleaner, more efficient C++ code.
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 ) {
    cout << *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.
 
C++:
using namespace std;
using vit = vector<string>::iterator;
void print(vector<string>& s) {
  for(vit it = s.begin(); it != s.end(); ++it ) {
    cout << *it << endl;
  }
}
 
  • Like
Likes Curtisc, jedishrfu and berkeman

Similar threads

Replies
3
Views
1K
Replies
2
Views
2K
Replies
2
Views
3K
Replies
8
Views
1K
Replies
3
Views
2K
Replies
7
Views
2K
Replies
2
Views
2K
Back
Top