まず、この記事を読んで助けてくれてありがとう。どのようにしてstd :: map type structからデータを取得できますか?
私はこの構造を持っています:x、y。 そして私はデータがその構造であるマップを持っています。 イテレータ[1] get .xなどのデータを取得したいとします。 どうすればいいですか?
ありがとうございます。
まず、この記事を読んで助けてくれてありがとう。どのようにしてstd :: map type structからデータを取得できますか?
私はこの構造を持っています:x、y。 そして私はデータがその構造であるマップを持っています。 イテレータ[1] get .xなどのデータを取得したいとします。 どうすればいいですか?
ありがとうございます。
あなたがstd::map<X, Y>
の要素を指すイテレータit
を持っているなら、あなたはit->first
を使用してキーとit->second
を使用してマップされた型への参照をconst参照を取得することができ、it
ポイント型であるstd::map<X, Y>::value_type
値にあるため例えば
std::pair<std::map<X, Y>::key_type const,
std::map<X, Y>::mapped_type>
:
Y * setX(std::map<X, X> & dict, X const & value) {
std::map<X, Y>::iterator it = dict.find(value);
if (it != dict.end())
return nullptr;
assert(it->first == value);
return &it->second;
}
#include <map>
#include <iostream>
#include <string>
using namespace std;
int main()
{
// for a simple struct you could use "pair" (especially if you don't want to name it).
// anyway:
map<int, pair<double, string>> mymap;
mymap[0] = pair<double, string>(4.56, "hello");
mymap[1] = pair<double, string>(9.87, "hi");
for(auto & item : mymap)
{
cout << "Key: " << item.first << ", Value: [" << item.second.first << ", " << item.second.second << "]" << endl;
}
return 0;
}
出力:
キー:0、値[4.56、ハロー]
キー:1、値[9.87、HI]