std::map, pointer to map key value, is this possible?
First, maps are guaranteed to be stable; i.e. the iterators are not invalidated by element insertion or deletion (except the element being deleted of course).
However, stability of iterator does not guarantee stability of pointers! Although it usually happens that most implementations use pointers - at least at some level - to implement iterators (which means it is quite safe to assume your solution will work), what you should really store is the iterator itself.
What you could do is create a small object like:
struct StringPtrInMap
{
typedef std::map<string,string>::iterator iterator;
StringPtrInMap(iterator i) : it(i) {}
const string& operator*() const { return it->first; }
const string* operator->() const { return &it->first; }
iterator it;
}
And then store that instead of a string pointer.
Pointers as keys in map C++ STL
The default implementation will compare the addresses stored by the pointers, so different objects will be considered as different keys. However, the logical state of the object will not be considered. For example, if you use std::string *
as the key, two different std::string
objects with the same text of "Hello"
would be considered a different key! (When stored in the map by their addresses)
It's ok to use pointers as keys so long as you understand the important difference above.
Is it wise to use a pointer to access values in an std::map
It would undoubtedly be more typical to return an iterator than a pointer, though it probably makes little difference.
As far as remaining valid goes: a map iterator remains valid until/unless the item it refers to is removed/erased from the map.
When you insert or delete some other node in the map, that can result in the nodes in the map being rearranged. That's done by manipulating the pointers between the nodes though, so it changes what other nodes contain pointers to the node you care about, but does not change the address or content of that particular node, so pointers/iterators to that node remain valid.
Accessing the values of map from its key using pointer to map
In your example, you haven't actually allocated any dictionary
or (std::unordered_map
) objects yet.
The dict_array[i]
is simply a null pointer. Thus the assignment to mydict
also results in a null pointer. You would need to construct a dictionary
first by invoking dict_array[i] = new dictionary();
.
The expression mydict[some_key]++
doesn't mean what you think it does because mydict
is a dictionary *
and not a dictionary
. Thus you would need to actually dereference it first before having access to a valid dictionary
object:
(*my_dict)[some_key]++
But again, before this would work, you need to initialize the underlying pointers.
Also, it's generally a bad idea (which often leads to undefined behavior) to mix C allocation with C++ standard objects.
How do I create a pointer to key/value pair of a map in C++?
mp.begin()
does not return a pointer, it returns an iterator, which is an object that represents a reference to an entry, but still an object in of itself.
You can convert an iterator into a pointer by using &*iterator
, which means "The address of (&
) the object referred to (*
) by that iterator".
Next up, map<string,string>*
is a pointer to the map itself. If you want a pointer to an entry within the map, you need to use map<string, string>::value_type*
.
Putting all that together, what you want is:
map<string, string>::value_type* pt = &*mp.begin();
Pointer to data that stored in a map container
This gets a pointer to a DATA value in the map, if present.
DataList::iterator it = myData.find( 42 );
DATA * pData = NULL;
if ( it != myData.end() ) {
pData = &((*it).second);
}
Pointer to Value in a std::map
You should use iterators:
mutex.lock();
std::map<int, Call>::iterator callptr = calls.find(id);
callptr->second.foo();
...
mutex.unlock();
Your first solution with pointers is problematic, because the lifetime of the object in the map is uncertain - it may be moved when the tree is rebalanced when elements are inserted or deleted.
Your second solution won't work at all, because std::auto_ptr
does not fulfil the requirements for mapped_type
of std::map
- mostly because its copy constructor and operator=
don't actually copy. You likely won't get a compiler error, but you'll get very weird behavior at run-time.
How can I access the elements of a pointer-to-map?
Due to operator precedence rules, *baa[1]
is parsed as *(baa[1])
instead of (*baa)[1]
. You could just put in the parentheses to make it work. However, you'd be better off using references instead:
void faa(map<int,string> &baa){
baa[1] = "somethingnew";
}
Then you just call the function without taking the address of the map:
faa(bar);
Passing pointer on vector's elements into map
If you want pointers, you'd have to take the address of your dereferenced iterators
s = &(*x);
sport = &(*y);
I would warn you, however, that this is a fragile design if you mutate your vectors allSportsmen
or allSports
(e.g. push_back
, emplace_back
, resize
, etc) that causes a reallocation, you'll likely invalidate your pointers.
Also note that you'd have to change the type of your map to store pointers
map<Sportsman*, vector<Sport*>> participants;
Set key and value of a map* in C++
You can de-reference the pointer:
(*m)[10] = 1;
or
m->operator[](10) = 1;
On the other hand, do you really need all these pointers? Would your program suffer greatly from using this form?
map<unsigned long long int, map<int, int>> invertID;
int main()
{
map<int,int> m;
invertID[1][10] = 1;
}
Related Topics
Is There a Good Python Library That Can Parse C++
What Is the Correct Way of Reading from a Tcp Socket in C/C++
Why Does Gcc Generate 15-20% Faster Code If I Optimize for Size Instead of Speed
Does Boost Have a Datatype for Set Operations That Is Simpler Than the Stl
How to Call a Function by Its Name (Std::String) in C++
How to Get Current Timestamp in Milliseconds Since 1970 Just the Way Java Gets
How Does the Range-Based for Work for Plain Arrays
What Is Better, Adjacency Lists or Adjacency Matrices for Graph Problems in C++
Should I Store Entire Objects, or Pointers to Objects in Containers
How to Have Swift, Objective-C, C and C++ Files in the Same Xcode Project
Qgraphicsview Zooming in and Out Under Mouse Position Using Mouse Wheel
Understanding Recursion to Generate Permutations
How to Properly Use Std::String on Utf-8 in C++
Does Std::Vector *Have* to Move Objects When Growing Capacity? Or, Can Allocators "Reallocate"
Why Does This Delay-Loop Start to Run Faster After Several Iterations with No Sleep