std::memcmp
From 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 の対応するバイトよりも小さい場合、負の値を返します。
0 lhs と rhs のすべての count バイトが等しい場合。
lhs の最初の異なるバイトが rhs の対応するバイトよりも大きい場合、正の値を返します。
[編集] 注意
この関数は、オブジェクトの値ではなく、オブジェクトの表現を読み取ります。通常、パディングのない、単純にコピー可能なオブジェクトに対してのみ意味があります。例えば、std::string または std::vector 型の 2 つのオブジェクト間のmemcmp() は、それらの内容を比較しません。型 struct { char c; int n; } の 2 つのオブジェクト間の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); 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
[編集] 関連項目
| 2つの文字列を比較する (関数) | |
| 2つの文字列から指定された文字数を比較する (関数) | |
| C のドキュメント(`memcmp` について)
| |