When to use "std::"

I’m currently in the 6th section of the C++ course (Functions) and I’m running into more occasions where I don’t understand when to use the “std::” portion in the code. I understand using it for ::cout and ::cin, but when/why do you include with with things like vector or string?

For example, I didn’t get this exercise right because I didn’t include std:: in front of string in…void name_x_times(std::string name, int x) {

Example of the full exercise below…

#include <iostream>

// Define name_x_times() below:
void name_x_times(std::string name, int x) {
  
  while (x > 0) {
    
    std::cout << name;
    x--;
    
  }
  
}

int main() {
  
  std::string my_name = "Add your name here!";
  int some_number = 5; // Change this if you like!
  // Call name_x_times() below with my_name and some_number
  name_x_times(my_name, some_number);
  
}

Recently I also had the same question and studied some about this. To understand this, we first need to know about namespaces. Here are links to articles that might be helpful:

The string and vector which we want to use are in the C++ standard library, so they belong to the std namespace. This is why you need to add std:: to them. It is the same reason to use std:: for cout and cin.

1 Like

Something else that helps out a lot is by typing:
using namespace std;
at the top of your entire program. That eliminates the use for std:: in anything. So you can just use cout instead of std::cout

1 Like

Interesting. Is that still considered “best practice”, or is this not something you typically can do?

I see it very often and I’d think that it’d save several keystrokes.

Importing the entire std namespace is generally considered a bad practice. You can Google it, and find many articles explaining why. You, the programmer, can decide for yourself whether you want to do it or not. One alternative is to only import the types or classes that you are going to use:

#include <iostream>
using std::cout;
using std::string;

string sayHi(string name) {
  return "Hello " + name + "!";
}
int main() {
  cout << "Hello World!\n";
  cout << sayHi("Thomas");
}
3 Likes