Searching and Inserting in a map with 3 elements in C++
I need to have a map like this :
typedef std::map<int, float , char> Maptype ;
What is the syntax to insert and searching elements of pa开发者_运维技巧ir in this map.
A map
can only map one key type to one data type. If the data contains 2 elements, use a struct or a std::pair
.
typedef std::map<int, std::pair<float, char> > Maptype;
...
Maptype m;
m[123] = std::make_pair(0.5f, 'c');
...
std::pair<float, char> val = m[245];
std::cout << "float: " << val.first << ", char: " << val.second << std::endl;
You cannot have three elements. The STL map
stores a key-value pair. You need to decide on what you are going to use as a key. Once done, you can probably nest the other two in a separate map and use it as:
typedef std::map<int, std::map<float, char> > MapType;
In order to insert in a map, use the operator[]
or the insert
member function. You can search for using the find
member function.
MapType m;
// insert
m.insert(std::make_pair(4, std::make_pair(3.2, 'a')));
m[ -4 ] = make_pair(2.4, 'z');
// fnd
MapType::iterator i = m.find(-4);
if (i != m.end()) { // item exists ...
}
Additionally you can look at Boost.Tuple.
Use either
std::map<std::pair<int, float>, char>
or
std::map<int, std::pair<float, char> >
whichever is correct.
精彩评论