std is a namespace, which is a named group of names. The C++ standard library places its names inside std, so std::cout is the output stream from the standard library, and std::string is its string type. The :: between them is the scope resolution operator. It tells the compiler to look for the name inside std.
Why namespaces exist
Namespaces keep names from colliding. Two libraries can each define a function called print, and as long as they live in different namespaces, a program can use both. Your own code can have its own names too.
namespace shop {
int count = 3;
}
namespace warehouse {
int count = 10;
}
// shop::count is 3 and warehouse::count is 10
Writing std:: in a program
#include <iostream>
#include <string>
int main() {
std::string name = "Ada";
std::cout << "Hello, " << name << '\n';
}
Each standard name is written with its prefix. The headers provide the names: <iostream> declares std::cout, and <string> declares std::string.
Most of the standard library lives in std. Containers such as std::vector, std::list and std::map are there, as are algorithms such as std::sort and utilities such as std::optional. Each one is declared by a header you include, such as <vector>, <list> or <map>.
Why many tutorials use using namespace std
Many beginner examples start with this line:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, " << "world" << endl;
}
using namespace std; lets you drop the prefix, so cout works without std::. That saves typing in a short program. The cost is that every name in std now sits alongside your own names, which can cause clashes. In a header file the cost is higher, because every file that includes the header gets the same effect.
If you want only one name without the prefix, bring in just that name:
using std::cout;
Common mistakes
- Forgetting the prefix. Writing
coutwithoutusingmakes the compiler report thatcoutis not declared. - Relying on indirect includes. Some code compiles on one compiler only because one header happens to include another. Include every header you use, such as
<string>forstd::string.
Key points
stdis the namespace that holds the C++ standard library.::is the scope resolution operator, sostd::coutmeanscoutinsidestd.- Keep the
std::prefix in headers and larger programs.using namespace std;is common in short examples.