2017-11-09 13 views
-1

こんにちは私はC++プログラムを使って文字列を属性としてマップに挿入しています。アルファベット順にソートしたオブジェクトを挿入する方法ソート済みのオブジェクトをマップに挿入する方法

以下のコードは、ベクターのサンプルコードです。私はマップを使用して同じを実装する必要があります

Word *WordVector::insert(const string text){ 
    Word newWord(text); 
    if(data.size()==0) 
    { 
     data.push_back(newWord); 
    } 

    else{ 
     auto insert_itr = std::lower_bound(data.begin(), data.end(),newWord); 
     if(insert_itr==data.end()||*insert_itr!=newWord){ 
      data.insert(insert_itr, newWord); 
     } 
     else newWord.increaseCount(); 
    } 
    return &newWord; 
} 

私はC++を初めて使っています。事前に助けてくれてありがとう。

また、このコードは私に予想よりも大きなベクトルサイズを与えています。どんな洞察が役に立つでしょう:)

+2

'のstd ::マップは常にソートされます。 'std :: unordered_map'もあります。 – DimChtz

+1

マップはソートされたコンテナです。キーと値が同じ場合、 'std :: set'を使いたいかもしれません。 – Ron

+0

質問を指定できますか?どのオブジェクトを挿入しますか?オブジェクトの文字列をキーとして挿入しますか? – FloIsAwsm

答えて

0

ちょうどstd::map<std::string, int>が必要なようです。新しいタイプのマップを作成する方法について

class WordContainer 
{ 
    std::map<std::string, int> words; 
    public: 
    void insert(const std::string & text) 
    { 
     ++words[text]; 
    } 
    int count(const std::string & text) 
    { 
     return words[text]; 
    } 
} 

元のテキスト:

あなたは、例えば、「構造体シング」を持っている想像してみましょう私たちはこのようなstd::map<Thing, T>を使用しようと

struct Thing 
{ 
    std::string name; // We need to keep Things in alphabetical order by name 
    int other_member; // etc 
}; 

今、私たちはコンパイルエラーになります、何かのように:私たちは私たちのマップに指定されていないので、これがある

/usr/local/include/c++/7.2.0/bits/stl_function.h:386:20: error: no match for 'operator<' (operand types are 'const Thing' and 'const Thing') 
     { return __x < __y; } 
       ~~~~^~~~~ 

方法Thingを注文しますsであり、デフォルトの<を使用してもThingのいずれの一致も見つかりません。

だから我々は比較が必要です。

struct Thing_less 
{ 
    bool operator()(const Thing & lhs, const Thing & rhs) 
    { 
     return lhs.name < rhs.name; 
    } 
} 

をそして、我々はmapタイプの一部としてこれを使用します。

int main() { 
    std::map<Thing, double, Thing_less> things; 
    things[{ "First", 1 }] = 1.5; 
    things[{ "Second", 2 }] = 3.14; 
    things[{ "Third", 3 }] = 0.0; 
    things[{ "Forth", 4 }] = 100.1; 

    for (auto & pair : things) 
    { 
     std::cout << pair.first.name << pair.second << "\n"; 
    } 

    return 0; 
} 

我々は結果を得る:

First 1.5 
Forth 100.1 
Second 3.14 
Third 0 
関連する問題