[英]Is assigning empty std::vector same as swaping for an empty std::vector?
[英]Difference between std::vector::empty and std::empty
要檢查向量v
是否為空,我可以使用std::empty(v)
或v.empty()
。 我查看了 cppreference 上的簽名,但缺乏理解它們的知識。 它們之間有什么關系? 一個實現調用另一個嗎?
我知道一個來自容器庫,另一個來自迭代器庫,但僅此而已。
std::vector::empty 和 std::empty 之間的區別
Container::empty
member function 和std::empty
free function(模板)之間的區別與Container::size
、 std::size
、 Container::data
、 std::data
、 Container::begin
、 std::begin
和Container::end
, std::end
。
在任何標准容器的所有這些情況下,免費 function(例如std::empty
)只需調用相應的成員 function。免費 function 存在的目的是提供容器之間的統一接口(以及std::initializer_list
) 和 arrays。Arrays 不能像 class 模板那樣擁有成員函數,所以它們對這些自由函數有專門的重載。
如果您正在使用模板化容器類型編寫代碼,那么您應該使用免費的 function 以便能夠支持數組作為模板化類型。 如果類型不是模板化的,那么除了可能重構為模板(或只是普通數組)的便利性之外,選擇使用成員 function 或免費 function 沒有區別。
std::empty
有三個重載,但std::empty(v)
用於向量v
的重載是第一個:
template <class C>
constexpr auto empty(const C& c) -> decltype(c.empty()); // (since c++17, until c++20)
template <class C>
[[nodiscard]] constexpr auto empty(const C& c) -> decltype(c.empty());
(since C++20) // (since c++20)
此重載具有以下效果:
- 返回
c.empty()
因此, std::empty(v)
和v.empty()
在這種情況下具有相同的效果。
std::empty
返回調用std::vector::empty
的結果。
std::empty
適用於容器可能會或可能不會為提供成員 function empty 的類型提供成員 function empty
empty()
的情況, std::empty
提供默認實現,但對於不提供此 function 的自定義類型,您可以在命名空間 scope 中提供一個empty
的 function 以供在模板中使用; 由於參數依賴查找,與參數相同的名稱空間中的 function 將用作后備:
namespace Custom
{
struct Container
{
bool m_empty;
};
constexpr bool empty(Container const& c) // custom implementation for our own type
{
return c.m_empty;
}
}
template<class T>
void PrintEmpty(char const* containerName, T&& container)
{
using namespace std;
std::cout << containerName << " is " << (empty(container) ? "empty" : "not empty") << '\n';
}
int main()
{
PrintEmpty("std::vector<int>()", std::vector<int>());
PrintEmpty("Container{}", Custom::Container{});
PrintEmpty("Container{ true }", Custom::Container{ true });
}
對於語言律師來說,C++20 標准說容器a
有它的a.empty()
成員true
當且僅當a.begin() == a.end()
([container.requirements 。一般的])。
std::empty()
非成員 function 在 [iterator.range] 中指定。 重載constexpr auto empty(const C& c)
“返回: c.empty()
”。
因此,在標准中,非成員 function 是根據成員函數指定的,反之亦然。 一般來說,這並不意味着實施需要讓非成員 function 實際上調用成員 function,只要它“表現得好像”。 在這種情況下,該關系必須適用於 STL 容器類的任何允許的特化,或適用於自定義容器類,以便限制允許庫的編寫者執行的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.