std::memcmp
出自cppreference.com
在標頭 <cstring> 定義
|
||
int memcmp( const void* lhs, const void* rhs, std::size_t count ); |
||
轉譯 lhs 和 rhs 所指向的對象為 unsigned char 數組,並比較這些數組的前 count 個位元組。按字典序比較。
結果的正負號是在被比較對象中首對相異的位元組值(都轉譯成 unsigned char)的差的正負號。
目錄 |
[編輯] 參數
lhs, rhs | - | 指向要比較的內存緩衝區的指針 |
count | - | 要檢驗的位元組數 |
[編輯] 返回值
在 lhs 中首個有差別的位元組(轉譯為 unsigned char)小於 rhs 中的對應位元組的情況下返回負值。
在 lhs 和 rhs 的所有 count 個位元組相等的情況下返回 0。
在 lhs 中首個有差別的位元組大於 rhs 中的對應位元組的情況下返回正值。
[編輯] 註解
此函數讀取對象表示,而非對象值,而且典型地只對無填充的可平凡複製對象有意義。例如兩個 std::string 或 std::vector 類型對象間的 memcmp()
將不比較它們的內容,而兩個 struct {char c; int n;} 類型對象間的 memcmp()
將比較填充位元組,它們的值在 c 和 n 相同時也可以不同,而且即使沒有填充位元組,可能在考慮端序的情況下比較 int
。
[編輯] 示例
運行此代碼
#include <cstring> #include <iostream> void demo(const char* lhs, const char* rhs, std::size_t sz) { std::cout << std::string(lhs, sz) << " 在字典序中"; int rc = std::memcmp(lhs, rhs, sz); if (rc == 0) std::cout << "与 " << std::string(rhs, sz) << " 比较相等\n"; else if (rc < 0) std::cout << "先于 " << std::string(rhs, sz) << '\n'; else if (rc > 0) std::cout << "后于 " << std::string(rhs, sz) << '\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 在字典序中先于 abd abd 在字典序中后于 abc abc 在字典序中与 abc 比较相等
[編輯] 參閱
比較兩個字元串 (函數) | |
比較兩個字元串的一定量字元 (函數) | |
memcmp 的 C 文檔
|