page_url:https://atcoder.jp/contests/apg4b/tasks/APG4b_ag
任务ID:3779
要点
- 名前空間允许您避免名称冲突
- 定义命名空间如下。
namespace 名前空間名 {
// 内容
}
- 访问命名空间内的变量和函数
通过
名前空間名::指定命名空间 - 命名空间可以嵌套
using namespace 名前空間名;通过名前空間名::可以省略- STL 函数和结构是
std在命名空间内定义 using namespace std;是 省略std::省略
- STL 函数和结构是
名前空間
为了避免函数、结构和全局变量的名称冲突, 可以定义名前空間。
以下程序定义了命名空间 A 和命名空间 B,并且在每个命名空间内部
定义了一个名为f的函数。
#include <bits/stdc++.h>
using namespace std;
// 名前空間A
namespace A {
void f() {
cout << "namespace A" << endl;
}
}
// 名前空間B
namespace B {
void f() {
cout << "namespace B" << endl;
}
}
int main() {
A::f(); // 名前空間A内の関数fの呼び出し
B::f(); // 名前空間B内の関数fの呼び出し
}
実行結果
namespace A namespace B
通过分离命名空间,可以像这样定义具有相同名称的函数。
调用函数时
在函数名称之前显式指定命名空间,例如A::f()。
在命名空间内,您可以定义函数、结构体、全局变量等。
命名空间定义
要定义命名空间,请编写:
namespace 名前空間名 {
// 内容
}
名称解析
要访问命名空间内定义的函数和变量,请指定命名空间名称,如下所示。
名前空間::関数名 名前空間::グローバル変数名 名前空間::構造体名
命名空间嵌套
您还可以嵌套命名空间。
#include <bits/stdc++.h>
using namespace std;
namespace A {
namespace B{
void f() {
cout << "A::B::f" << endl;
}
}
void f() {
cout << "A::f" << endl;
}
}
int main() {
A::f();
A::B::f();
}
実行結果
A::f A::B::f
使用命名空间 通过编写
using namespace 名前空間名;,您可以省略指定该范围内的命名空间。
#include <bits/stdc++.h>
using namespace std;
namespace A {
void f() {
cout << "A::f" << endl;
}
}
int main() {
using namespace A;
f(); // A::f();と書くのと同じ
}
実行結果
A::f
使用命名空间 std;
到目前为止的解释中,它被写在程序的第二行。
您可以理解using namespace std;的含义。
STL 函数和结构是
它在命名空间std内定义。
因此,本来,要使用STL函数,就必须指定名称。
必须以std::为前缀。
通过写
using namespace std;现在可以省略std::。
using namespace std;在编写小型程序时很有用,但是
随着规模的增大,名称冲突变得难以避免,因此
到全球范围
您应该避免写using namespace std;。
如果您添加前缀
std::,
您可以在不写入using namespace std;的情况下编写程序。
不使用命名空间 std 的示例
#include <bits/stdc++.h>
int main() {
std::vector<int> a = {3, 4, 1, 2};
std::sort(a.begin(), a.end());
for (int i = 0; i < a.size(); i++) {
std::cout << a.at(i) << std::endl;
}
}
実行結果
1 2 3 4
详细信息
命名空间别名
您可以指定嵌套命名空间并为长命名空间名称提供别名。
#include <bits/stdc++.h>
using namespace std;
namespace A {
namespace B {
namespace C {
void f() {
cout << "A::B::C::f" << endl;
}
}
}
}
namespace too_long_name {
void f() {
cout << "too_long_name::f" << endl;
}
}
int main() {
namespace abc = A::B::C;
abc::f();
namespace s = too_long_name;
s::f();
}
実行結果
A::B::C::f too_long_name::f