W
W
wasserbord2018-05-22 16:25:57
C++ / C#
wasserbord, 2018-05-22 16:25:57

C++ how to copy tuples from one container to another via an iterator?

So.

struct my_tuple_hasher
{
  std::size_t operator()(const std::pair<std::string, std::string>& k) const
  {
    std::string s1, s2, s3;
    std::tie(s1, s2, s3) = k;
    return  std::hash<std::string>()(s1) ^ std::hash<std::string>()(s2) ^ std::hash<std::string>()(s3);
  }
};

std::unordered_map<std::tuple<std::string, std::string, std::string>, std::unique_ptr<SOMETHING>, my_tuple_hasher> m;

Here we have an unordered_map with a tuple of 3 rows as the key and a unique_ptr smart pointer as the value.
I implemented the hash for unordered_map, see above.
We fill in:
auto ob02 = std::unique_ptr<SOME_TYPE>(new SOME_TYPE());
ob02->... = ...;
m[std::make_tuple("Lorem", "ipsum", "1")] = std::move(ob02);

No problem.
And now we have another unordered_map named m2, exactly the same type, but empty for now.
And you need to throw all the elements into it. (This is NOT a copy, it will then merge several maps into 1):
for (auto it = m.begin(); it != m.end(); ++it)
{
    m2[it->first] = std::move(it->second);
}

And here is the problem. Swears! Still, after all, first instead tuple<string, string, string>returns some kind of tr1::tuple<...>
And I am forced, like an idiot, to unpack it-> first through tie, make a new tuple from the values ​​​​and put it in a new map - and so each tuple.
For example, with std::pair there is no such problem.
What to do? Nested std::pair etc. do not offer, only stupid.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly, 2018-05-22
@vt4a2h

1) Your hash operator just won't compile. You are trying to decompose a pair into three arguments.
2) In the hashing operator, the combination of hashes is not quite correct. See how boost::hash_combine is made, for example.
3) Check if the types are exactly the same. Better yet, create aliases for all long types and use them.
4) In principle, everything should work, and perhaps the problem is in the environment / flags. Get an online compiler like godbolt.org and try compiling there.
PS
I hope you are just experimenting and not writing a real project. This use of tuples is an overkill.
PPS
And English pronunciation tapl.

A
Alexander Yudakov, 2018-05-22
@AlexanderYudakov

At me nothing swears. VS 2013.
The compiler's mention of "tuple" from the "tr1" namespace probably indicates that it's time for you to upgrade your tooling.
And probably instead of:
you wanted to do:

std::size_t operator()(const std::tuple<std::string, std::string, std::string>& k) const

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question