2016-09-09 4 views
1

私はまだプログラミングが比較的新しいですし、これを実装する方法について多くの研究を行っていますが、わかりません。大文字と小文字を区別しないすべてのデータ型を受け入れるC++ソート?

私はこのケースを使用してきた小文字を区別しないソート:

for (size_t i = 0; i < copy.size() - 1; i++) //use copy vector to organize in ascending order 
    { 
     int smallest = i; 
     for (size_t j = i + 1; j < copy.size(); j++) 
     { 
      if (tolower(copy[j]) < tolower(copy[smallest])) //normalizes capitals and lowercases 
       smallest = j; 
     } 
     int temp = copy[smallest]; 
     copy[smallest] = copy[i]; 
     copy[i] = temp; 
    } 

私は文字列型のベクトルを渡すまでは正常に動作し、まだそれ大文字と小文字を区別しながら、私はすべてのデータ型のための普遍的な、この並べ替えを行うことができますどのように。 ?

+5

* * "すべてのデータ型のための普遍的なまだそれは大文字と小文字を区別しながら"。大文字小文字の区別がないのは、文字や文字列の意味だけであり、すべてのデータ型ではありません。 – michalsrb

+0

related/dupe:http://stackoverflow.com/questions/11635/case-insensitive-string-comparison-in-c – NathanOliver

+0

キャストの無感性は文字と文字列に適用されますが、私のベクトルはintに初期化されることがありますこれまでどおりに働くことができます。 – Olivia

答えて

2

std::sort()を独自の比較機能で使用できます。

さて、あなたは必要ないと思います。すべてのデータ型で大文字と小文字を区別しません。

あなたのコメントについて:デフォルトの比較をしたい場合は、常に3番目のパラメータを無視することができます。

例:

#include <string> 
#include <algorithm> 
#include <iostream> 
#include <vector> 
#include <cctype> //toupper 
using namespace std; 

bool CompareStringCaseInsensitive(const string& lhs,const string& rhs){ 

    string::size_type common_length = std::min(lhs.length(),rhs.length()); 

    for(string::size_type i=0;i<common_length;++i){ 
     if(toupper(lhs[i]) < toupper(rhs[i]))return true; 
     if(toupper(lhs[i]) > toupper(rhs[i]))return false; 
    } 

    if(lhs.length()<rhs.length())return true; 
    if(lhs.length()>rhs.length())return false;//can ignore 

    return false;//equal should return false 
} 

int main(){ 
    vector<string> testdata{"a","B","c","D"}; 

    cout << "Sort By Default :" << '\n'; 
    sort(testdata.begin(),testdata.end()); 
    for(const auto& s : testdata){cout << s << ' ';} 
    cout << '\n'; 

    cout << "Sort CaseInsensitive :" << '\n'; 
    sort(testdata.begin(),testdata.end(),CompareStringCaseInsensitive); 
    for(const auto& s : testdata){cout << s << ' ';} 
} 
+0

したがって、sortの3番目のパラメータでは、ここで使用されているような関数を呼び出す必要があります:http://stackoverflow.com/questions/11635/case-insensitive-string-comparison-in-c – Olivia

+0

ブーストを使用したくない場合は、独自に実装することができます。 –

関連する問題