質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.31%
VC++

VC++ (Visual C++) とは、Microsoft製のC++のための統合開発環境です。

C++

C++はC言語をもとにしてつくられた最もよく使われるマルチパラダイムプログラミング言語の1つです。オブジェクト指向、ジェネリック、命令型など広く対応しており、多目的に使用されています。

Q&A

解決済

1回答

516閲覧

static const std:mapから値を取得するには

退会済みユーザー

退会済みユーザー

総合スコア0

VC++

VC++ (Visual C++) とは、Microsoft製のC++のための統合開発環境です。

C++

C++はC言語をもとにしてつくられた最もよく使われるマルチパラダイムプログラミング言語の1つです。オブジェクト指向、ジェネリック、命令型など広く対応しており、多目的に使用されています。

0グッド

0クリップ

投稿2023/09/13 03:53

編集2023/09/13 03:59

発生している問題

std::mapの値を取得したいのですが以下のソースですとエラーになってしまいます。
取得側のconstをつけたり外したり,参照をやめたり、いろいろ試したのですが解決しません。
何かお気づきの方がいらっしゃいましたら教えてほしいです。
VC++17を使用

C++

1void test( void ) 2{ 3 static const std::map<std::string, std::vector<int>> tMap ={ 4 { "AAA", { 0, 1, 2, 3 } }, 5 { "BBB", { 1, 2, 3, 4 } } 6 }; 7 8 const std::vector<int>& test1 = tMap["AAA"]; // <---- エラーになる 9}

エラーメッセージ

error C2678: 二項演算子 '[': 型 'const std::map<std::string,std::vector<_type,std::allocator<int>>,std::lessstd::string,std::allocator<std::pair<const std::string,std::vector<_type,std::allocator<int>>>>>' の左オペランドを扱う演算子が見つかりません (または変換できません) (新しい動作; ヘルプを参照)。
with
[
_type=int
]
message : 'std::vector<_type,std::allocator<int>> &std::map<std::string,std::vector<_type,std::allocator<int>>,std::lessstd::string,std::allocator<std::pair<const std::string,std::vector<_type,std::allocator<int>>>>>::operator [](const std::basic_string<char,std::char_traits<char>,std::allocator<char>> &)' の可能性があります
with
[
_type=int
]
message : または 'std::vector<_type,std::allocator<int>> &std::map<std::string,std::vector<_type,std::allocator<int>>,std::lessstd::string,std::allocator<std::pair<const std::string,std::vector<_type,std::allocator<int>>>>>::operator [](std::basic_string<char,std::char_traits<char>,std::allocator<char>> &&)'
with
[
_type=int
]
message : 引数リスト '(const std::map<std::string,std::vector<_type,std::allocator<int>>,std::lessstd::string,std::allocator<std::pair<const std::string,std::vector<_type,std::allocator<int>>>>>, const char [4])' を一致させようとしているとき
with
[
_type=int
]
error C2530: 'test1': 参照が初期化されずに宣言されています。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

find()してend()じゃなければit->secondにアクセスしてください。

C++

1auto found = tMap.find("AAA"); 2if(found != tMap.end()) 3{ 4 auto& value = found->second; 5}

operator[]は、指定キーに該当する要素がなければ追加する仕様なので、非constです。
https://cpprefjp.github.io/reference/map/map/op_at.html

投稿2023/09/13 07:07

ttact

総合スコア171

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2023/09/13 08:29

ありがとうございます! atでいけました!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.31%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問