[英]What is the best method to compare two vectors of CString
我正在嘗試找到與CString的std向量進行比較的最有效,最優化和最快的方法。 有問題的字符串區分大小寫。 我曾嘗試對向量容器使用==運算符,但有時會返回誤報。 我的意思是,例如,如果一個向量包含順序為(a,b,c)的元素,而另一個向量包含順序為(b,c,a)的元素,則即使它們共享相同的數據,==運算符也將返回false。 另一件事是,它不區分大小寫。
我已經考慮過使用像這樣的基本嵌套循環方法:
//Not Tested
BOOL bMatch = TRUE;
for(int i=0; i<Vec1.size();i++)
{
if(!bMatch)
break;
int nComp=0;
for(int j=0;j<Vec2.size();j++)
{
if(vec1[i].CompareNoCase(Vec2[j])==0)
{
//We have a match--check next item
break;
}
else
{
nComp++;
if(nComp == Vec2.size()-1)
{
//Reached end of vector and no match found
//Vectors don't match
bMatch=FALSE;
}
}
}
}
上面的代碼未經過測試,我不確定是否有更好的方法可以在不使用嵌套循環的情況下實現這種比較。
不勝感激任何建議或幫助...
如果一個向量包含順序為(a,b,c)的元素,而另一個向量包含順序為(b,c,a)的元素,則即使它們共享相同的數據,==運算符也將返回false。
只需將數據插入順序無關緊要的兩個容器中,然后進行比較:
std::vector<CString> vec1;
std::vector<CString> vec2;
// ...
std::multiset<CString> set1(vec1.begin(), vec1.end());
std::multiset<CString> set2(vec2.begin(), vec2.end());
bool equal_data = (set1 == set2);
如果您想忽略大小寫(問題中的代碼似乎暗示了這種情況),則可以使用適當的比較器對std::multiset
和std::equal
進行參數化:
struct compareNoCase
{
bool operator()(const CString& a, const CString& b)
{
return a.CompareNoCase(b);
}
};
std::vector<CString> vec1;
std::vector<CString> vec2;
// ...
std::multiset<CString> set1(vec1.begin(), vec1.end(), compareNoCase());
std::multiset<CString> set2(vec2.begin(), vec2.end(), compareNoCase());
bool equal_data = std::equal(set1.begin(), set1.end(),
set2.begin(),
compareNoCase());
std::multiset
的參數化可確保將同一向量中的“ hello”和“ HELLO”視為一個值,而std::equal
的參數化可在兩個向量中保證這一點。
最后,如果您知道在同一vector
中沒有元素出現兩次,則可以使用set
而不是multiset
。 請注意,最好從一開始就使用set
或多multiset
。
如果(a,b,c)和(b,c,a)對您來說都是相同的,那么vector是一個不好的選擇,請改用std::set
或std::multiset
,並std::multiset
,將它們與std::equal
進行比較std::equal
,並將strcmp
作為比較器參數傳遞。 如果使用CString表示C樣式的以null終止的char數組,則此答案有效。 如果CString表示MFC CString,則FredOverflow的答案很完美。
首先使用std :: sort對它們進行排序,然后將它們與std :: equal進行比較。
不要使用簡單的for循環。 相反,您可以使用迭代器從兩個向量中檢索元素,然后使用_tcscmp或wcscmp比較值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.