altrko's blog

By altrko, history, 4 months ago, In English

recently i solved a problem which needed some answers on given pairs (each one of them) and i did it on sorted pairs and only normal way to get my answer (on unsorted pairs) was to create pair <pair<int,int>,int> p[2e5]. third int was for the index of unsorted pairs. so by sorting the pairs ,index automatically followed it and eventually i did it but code got messy and "time consuming" like p[i].first.second. Is there a better way of doing this?

  • Vote: I like it
  • +1
  • Vote: I do not like it

»
4 months ago, # |
  Vote: I like it +4 Vote: I do not like it

I suggest using struct.

»
4 months ago, # |
  Vote: I like it +3 Vote: I do not like it

use struct or array<int, 3>

»
4 months ago, # |
Rev. 3   Vote: I like it +8 Vote: I do not like it

Use array<int, 3>, vector<int> or own struct.

Guess array<int, 3> is the best solution. Just create array<int, 3> p[(int)2e5] and get elements by p[i][j].

struct is also a good solution, If you need to sort, you should make comparators for it.

vector<int> is also ok, but you need to initialize it manually.

You can also use tuple<int, int, int>, but i'd never use it because of std::get<i>(tuple).

  • »
    »
    4 months ago, # ^ |
      Vote: I like it +3 Vote: I do not like it

    thank you

  • »
    »
    4 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Can you explain the part "i'd never use it because of std::get(tuple)" ?

    • »
      »
      »
      4 months ago, # ^ |
        Vote: I like it +6 Vote: I do not like it

      It’s very annoying to type x= get<2>(myTuple) rather than x = a[2].

    • »
      »
      »
      4 months ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      sandbag is right. Writing get<0>(tuple) is annoying. Why should I write this function with uncommon template, when I can just access element by [0] in array<int, 3> or vector<int> or by defining own elements in struct. I'd like to have clearer code when I write it.

  • »
    »
    4 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    But you can use structured binding.

»
4 months ago, # |
  Vote: I like it 0 Vote: I do not like it

class with public attributes or structure work successfully in this situation

»
4 months ago, # |
  Vote: I like it 0 Vote: I do not like it

tuple<int, int, int> also works, though the convention of get<i>(p) ($$$0 \le i \le 2$$$) might be quite off-key compared to struct or pair.

At least for C++17 and above (maybe C++14 as well, I didn't test), you can always do something like this and save the hassle:

tuple<int, int, int> t;
// some definition for t
auto [item1, item2, item3] = t;