名稱空間
變體
操作

std::memcmp

來自 cppreference.com
< cpp‎ | string‎ | byte
在標頭檔案 <cstring> 中定義
int memcmp( const void* lhs, const void* rhs, std::size_t count );

lhsrhs 指向的物件重新解釋為 unsigned char 陣列,並比較這些陣列的前 count 個位元組。比較按字典序進行。

結果的符號是被比較物件中第一對不同位元組(都解釋為 unsigned char)的值的差的符號。

目錄

[編輯] 引數

lhs, rhs - 指向要比較的記憶體緩衝區的指標
count - 要檢查的位元組數

[編輯] 返回值

如果 lhs 中第一個不同位元組(重新解釋為 unsigned char)小於 rhs 中的對應位元組,則返回負值。

如果 lhsrhs 的所有 count 個位元組都相等,則返回 0

如果 lhs 中第一個不同位元組大於 rhs 中的對應位元組,則返回正值。

[編輯] 注意

此函式讀取物件表示,而不是物件值,並且通常僅對沒有填充的平凡可複製物件有意義。例如,對兩個 std::string 型別或 std::vector 型別的物件執行 memcmp() 不會比較它們的內容;對兩個 struct { char c; int n; } 型別的物件執行 memcmp() 將比較填充位元組,這些位元組的值可能在 cn 的值相同時不同,即使沒有填充位元組,int 也將在不考慮位元組序的情況下進行比較。

[編輯] 示例

#include <cstring>
#include <iostream>
 
void demo(const char* lhs, const char* rhs, std::size_t sz)
{
    std::cout << std::string(lhs, sz);
    const int rc = std::memcmp(lhs, rhs, sz);
    if (rc < 0)
        std::cout << " precedes ";
    else if (rc > 0)
        std::cout << " follows ";
    else
        std::cout << " compares equal to ";
    std::cout << std::string(rhs, sz) << " in lexicographical order\n";
}
 
int main()
{
    char a1[] = {'a', 'b', 'c'};
    char a2[sizeof a1] = {'a', 'b', 'd'};
 
    demo(a1, a2, sizeof a1);
    demo(a2, a1, sizeof a1);
    demo(a1, a1, sizeof a1);
}

輸出

abc precedes abd in lexicographical order
abd follows abc in lexicographical order
abc compares equal to abc in lexicographical order

[編輯] 參閱

比較兩個字串
(function) [編輯]
比較兩個字串的特定數量的字元
(function) [編輯]
C 文件 用於 memcmp