the below code shows how a structure binding normally works. It provides a more descriptive name comparing to "first", "second".
map<string, string> sites;
sites.insert({ "GeeksforGeeks", "Coding Resources" });
for (auto& [key, value] : sites)
{
cout << key.c_str() << " " << value.c_str() << endl;
}
Now I have a std::vector<pair<std::string, People>* > vec;
People
here is a class, and string
is his/her nicknames.
Code like following does not work, because vec
contains pointers.
for (auto & [kay, value] : vec) {}
Then what should I do to use the structure binding to provide more descriptive names?
Edit:
I use pointers because I want to avoid copies.
This is how I build the std::vector<pair<std::string, People>* > vec;
.
I have a unordered_map<string, People>
, I need to print the results to clients in a deterministic way, but traversing order of a map is random.
So, I create vec
and sort the vec
by the string, which is the key.
If not using pointers, lots of copies will happen if I want to sort.
You can do the following to the std::vector<pair<std::string, People>* > vec;
for (std::pair<std::string, People>* pairPtr : vec) // iterate via pair-ptrs
{
if (pairPtr) // if the pointer is valid!
{
const auto& [key, people] = *pairPtr;
// do something with the key and vale!
}
}
If the pair-pointer pointing to the array, you need to iterate through and do the above.
BTW, have a look at to the smart pointers rather raw pointer in C++17.