1

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.

JeJo
  • 30,635
  • 6
  • 49
  • 88
Lin Paul
  • 49
  • 8
  • you'll have to iterate over the pointers and defer the structured binding to within the loop, there is no syntax for dereferencing in structured bindings nor range-based for loops – kmdreko Aug 07 '20 at 05:39
  • I use pointer it is because I want to avoid copies. – Lin Paul Aug 07 '20 at 05:52
  • 1
    Did you mean that you do not what to make a [deep copy `std::pair`](https://stackoverflow.com/questions/2657810/deep-copy-vs-shallow-copy) rather just a copy of the pointers what the vec hold. Sounds not good. Anyways, that is another issue/question. – JeJo Aug 07 '20 at 05:54
  • I updated the problem. It provides more information. :) – Lin Paul Aug 07 '20 at 05:56
  • If the answer helped you solved the issue, you could mark it as accepted. Otherwise let me know, what is missing... – JeJo Aug 08 '20 at 21:44

1 Answers1

4

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.

JeJo
  • 30,635
  • 6
  • 49
  • 88