2016-10-30 8 views
-2

大丈夫なので、私はどのように2つの単語の文字列(bigram)からマップキーを作成しようと思っています。たとえば、「This is a test」という行です。 「これだけです」、「だけです」、「だけ」、「テスト」のバイグラムが含まれています。C++のマップキーとしてのビッグラム

私はmake_pairを使用することを考えていますが、これにより、これらのバイグラムが順不同で作成される可能性があることがわかります。これが事実だろうか?そうでない場合、このペアリングのアプローチは適切な軌道上にあるでしょうか?

+0

ほとんどすべてのデータ構造を使用してbigramを格納できます。 'std :: vector '、 'std :: tuple '/'std :: pair '、 'std :: list 'などは、あなたがそれらで何をしたいかによって、すべての有効かつ合理的な選択肢です。 – erip

答えて

1

std::pairは本来バイナリなので、私はこれをお勧めします。トライグラムや4グラムが必要な機会がある場合は(非公式に言えば)の一般化であるstd::tupleに固執することができます。

bigramアルゴリズムが正しい限り、その注文は保存されます。そこ作ることができるいくつかの明白な改善点がありますが、私はここで迅速な実装を書いた:

#include <iostream> 
#include <vector> 
#include <string> 
#include <iterator> 
#include <map> 
#include <sstream> 
#include <utility> 

std::vector<std::string> tokenize(const std::string& s) { 
    std::istringstream iss(s); 

    std::vector<std::string> v{std::istream_iterator<std::string>(iss), 
           std::istream_iterator<std::string>()}; 
    return v; 
} 

std::vector<std::pair<std::string, std::string>> make_bigrams(const std::vector<std::string>& tokens) { 
    std::vector<std::pair<std::string, std::string>> bigrams; 
    for(auto it = std::cbegin(tokens); it != std::prev(std::cend(tokens)); ++it) { 
     bigrams.push_back(std::make_pair(*it, *std::next(it))); 
    } 
    return bigrams; 
} 

std::vector<std::pair<std::string, std::string>> sentence_bigram(const std::string& s) { 
    const auto toks = tokenize(s); 
    return make_bigrams(toks); 
} 

int main() { 
    const auto& bigrams = sentence_bigram("hello, world. my name is erip"); 
    std::map<std::pair<std::string, std::string>, int> m; 
    for(const auto& e: bigrams) { 
     std::cout << "Adding (" << e.first << "), (" << e.second << ") to the map.\n"; 
     m[e] = 0; 
    } 
} 

、あなたはアクションhereでそれを見ることができます。

+0

助けてくれてありがとう!あなたの助けに感謝! –

関連する問題