Accessing map value by index
Your map
is not supposed to be accessed that way, it's indexed by keys not by positions. A map
iterator is bidirectional, just like a list
, so the function you are using is no more inefficient than accessing a list
by position. If you want random access by position then use a vector
or a deque
.
Your function could be written with help from std::advance(iter, index)
starting from begin()
:
auto it = myMap.begin();
std::advance(it, index);
return it->first;
Java HashMap: How to get a key and value by index?
You can iterate over keys by calling map.keySet()
, or iterate over the entries by calling map.entrySet()
. Iterating over entries will probably be faster.
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
List<String> list = entry.getValue();
// Do things with the list
}
If you want to ensure that you iterate over the keys in the same order you inserted them then use a LinkedHashMap
.
By the way, I'd recommend changing the declared type of the map to <String, List<String>>
. Always best to declare types in terms of the interface rather than the implementation.
Index inside map() function
You will be able to get the current iteration's index
for the map
method through its 2nd parameter.
Example:
const list = [ 'h', 'e', 'l', 'l', 'o'];
list.map((currElement, index) => {
console.log("The current iteration is: " + index);
console.log("The current element is: " + currElement);
console.log("\n");
return currElement; //equivalent to list[index]
});
Output:
The current iteration is: 0 <br>The current element is: h
The current iteration is: 1 <br>The current element is: e
The current iteration is: 2 <br>The current element is: l
The current iteration is: 3 <br>The current element is: l
The current iteration is: 4 <br>The current element is: o
See also: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Parameters
callback -
Function that produces an element of the new Array, taking three arguments:1) currentValue
The current element being processed in the array.2) index
The index of the current element being processed in the array.3) array
The array map was called upon.
Getting Map Value Pairs Using Index
Well you can write a method to do this.
public static <K, V> Map.Entry<K, V> getEntryByIndex(Map<K, V> map, int i) {
if(i >= map.size()) {
throw new IndexOutOfBoundsException(String.valueOf(i));
}
// use Iterator
Iterator<Map.Entry<K, V>> it = map.entrySet().iterator();
// skip to i
for(; i > 0; --i) {
it.next();
}
return it.next();
}
This pretty much treats it like a linked list. If you are finding you do this a lot you may want to permanently keep an ArrayList along with the Map.
C++ std::map how to access keys by index location
You can use Boost.MultiIndex's ranked indices:
Live On Coliru
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ranked_index.hpp>
#include <boost/multi_index/member.hpp>
using namespace boost::multi_index;
template<typename K,typename T>
using ranked_map=multi_index_container<
std::pair<K,T>,
indexed_by<
ranked_unique<member<std::pair<K,T>,K,&std::pair<K,T>::first>>
>
>;
#include <cassert>
#include <string>
int main()
{
ranked_map<std::string,std::string> m;
m.emplace("a","value for a");
m.emplace("b","value for b");
assert(m.nth(0)->first=="a");
assert(m.nth(1)->first=="b");
assert(m.nth(1)->second=="value for b");
assert(m.find("a")->second=="value for a");
}
Note, however, that nth
is not O(1) but logarithmic, so ranked indices are not exactly random-access.
Postscript: Another alternative with true random access is Boost.Container's flat associative containers:
Live On Coliru
#include <boost/container/flat_map.hpp>
#include <cassert>
#include <string>
int main()
{
boost::container::flat_map<std::string,std::string> m;
m["a"]="value for a";
m["b"]="value for b";
assert(m.nth(0)->first=="a");
assert(m.nth(1)->first=="b");
assert(m.nth(1)->second=="value for b");
assert(m["a"]=="value for a");
}
The downside here is that insertion takes linear rather than logarithmic time.
Related Topics
Getchar_Unlocked( ) VS Scanf() VS Cin
How to Create and Initialize an Array of Values Using Template Metaprogramming
Forcing Nvidia Gpu Programmatically in Optimus Laptops
How to Convert Typename T to String in C++
Garbage Collection Libraries in C++
Using Emit VS Calling a Signal as If It's a Regular Function in Qt
How to Force Inclusion of an Object File in a Static Library When Linking into Executable
What's the Best Way to Check If a File Exists in C++? (Cross Platform)
How Does C++ Exception Handling Translate to MAChine Code
Difference in Initializing and Zeroing an Array in C/C++
Opinions on Type-Punning in C++
Add Application to Startup (Registry)
C++ Concatenating _File_ and _Line_ MACros