2017-10-02 10 views
1

std::mapを使用して、ラテンアルファベットの各文字にintタイプ値を割り当てようとしています。私は新しいint型を作成し、それを言葉にマッピングされたintに等しい値を与えたいときに、私はエラーを取得:エラー:charからconst key_typeへのユーザー定義の変換が無効です&

F:\Programming\korki\BRUDNOPIS\main.cpp|14|error: invalid user-defined conversion from 'char' to 'const key_type& {aka const std::basic_string&}' [-fpermissive]|

例:私は間違って何をやっている

#include <iostream> 
#include <string> 
#include <cstdlib> 
#include <map> 

using namespace std; 

int main() 
{ 
    std::map <std::string,int> map; 
    map["A"] = 1; 
    int x; 
    std:: string word = "AAAAAA"; 
    x = map[word[3]]; 

    cout << x; 

    return 0; 
} 

+0

@ juanchopanza - あなたが正しいです。しかし...私の答えはとても些細だった...削除されました。 – max66

答えて

1

I am trying to assign int type value to each letter in latin alphabet using std::map.

。今、あなたは鍵がstd::stringあるstd::mapのキーとしてcharを使用しようとしている

#include <iostream> 
#include <string> 
#include <map> 

int main() 
{ 
    std::map<char, int> map; 
    map['A'] = 1; 
    int x; 
    std:: string word = "AAAAAA"; 
    x = map[word[3]]; 

    std::cout << x << std::endl; 

    return 0; 
} 

他者によって観察されたように、のようなもの。そして、charからstd::stringへの自動変換はありません。

Little Offトピックの提案:mapという名前のstd::mapのように、変数に同じタイプの名前を指定しないでください。正当だが混乱しやすい。

0

word[3]のタイプはcharで、マップのキーはstd::stringです。 charからstd::stringへの変換はありません。

ただ、この変更によって、(string::substrを使用して)文字列の部分文字列を取る:あなたのキーとしてcharを使用し、まだ

x = map[word.substr(3, 1)]; 

またはそれ以上:これに

x = map[word[3]]; 

をあなたの手紙が必要なので、このように:

std::map <char, int> map; 
map['A'] = 1; 
// rest of the code as in your question 
0

word[3]は、文字列の4番目の文字です。しかし、マップは文字列をキーとして使用するため、マップのキーとしては使用できません。あなたは文字のキーを持っているマップを変更する場合、それは動作しますか、次のことができます。

  • 単語から文字列を作成する[3]
  • 使用SUBSTR(3,1)キー
  • を取得しますあなたがマップのキーとして char(代わりの std::string)を使用する必要がありますので、
関連する問題