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 … Read more

Using a C string gives a warning: “Address of stack memory associated with local variable returned”

Variable char* matches[1]; is declared on the stack, and it will be automatically released when the current block goes out of scope. This means when you return matches, memory reserved for matches will be freed, and your pointer will point to something that you don’t want to. You can solve this in many ways, and … Read more

C++ inserting unique_ptr in map

As a first remark, I wouldn’t call it ObjectArray if it is a map and not an array. Anyway, you can insert objects this way: ObjectArray myMap; myMap.insert(std::make_pair(0, std::unique_ptr<Class1>(new Class1()))); Or this way: ObjectArray myMap; myMap[0] = std::unique_ptr<Class1>(new Class1()); The difference between the two forms is that the former will fail if the key 0 … Read more

How to access the contents of a vector from a pointer to the vector in C++?

There are many solutions, here’s a few I’ve come up with: int main(int nArgs, char ** vArgs) { vector<int> *v = new vector<int>(10); v->at(2); //Retrieve using pointer to member v->operator[](2); //Retrieve using pointer to operator member v->size(); //Retrieve size vector<int> &vr = *v; //Create a reference vr[2]; //Normal access through reference delete &vr; //Delete the … Read more