Блог пользователя altrko

Автор altrko, история, 3 недели назад, По-английски

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?

  • Проголосовать: нравится
  • +1
  • Проголосовать: не нравится

»
3 недели назад, # |
  Проголосовать: нравится +4 Проголосовать: не нравится

I suggest using struct.

»
3 недели назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

use struct or array<int, 3>

»
3 недели назад, # |
Rev. 3   Проголосовать: нравится +8 Проголосовать: не нравится

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).

  • »
    »
    3 недели назад, # ^ |
      Проголосовать: нравится +3 Проголосовать: не нравится

    thank you

  • »
    »
    3 недели назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

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

    • »
      »
      »
      3 недели назад, # ^ |
        Проголосовать: нравится +6 Проголосовать: не нравится

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

    • »
      »
      »
      3 недели назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

      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.

  • »
    »
    3 недели назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    But you can use structured binding.

»
3 недели назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

class with public attributes or structure work successfully in this situation

»
3 недели назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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;