1

In competitive programming, I see people initializing vector of pairs like below:

#include <bits/stdc++.h>
using namespace std;

typedef pair<int, int> ii;
typedef vector<ii> vii;

vector<vii> AL;
int main(){
  int V, E; scanf("%d %d", &V, &E);
  AL.assign(V, vii());
}

I want to ask about AL.assign(V, vii()); I know that it is going to have V pairs in AL, but what's the meaning of vii() here?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • See `std::vector::assign` form (1) [here](https://en.cppreference.com/w/cpp/container/vector/assign). It's the `value`. – Drew Dormann Jul 08 '21 at 17:04
  • `vii()` constructs a temporary variable that will be used in the `assign` method and then go out of scope. Fortunately a copy is made of the temporary (assuming the compiler doesn't do some time-saving trickery) so `AL` isn't left referring to dead space. – user4581301 Jul 08 '21 at 17:05
  • 3
    Side note: Competition code's not the easiest stuff to learn from. It's intended to be written fast and run once. Comprehensibility is way down on the competitor's priority list. – user4581301 Jul 08 '21 at 17:07
  • Read and learn: [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/2752075), [Why should I not #include ?](https://stackoverflow.com/q/31816095/2752075). Also prefer `using` to `typedef`, e.g. `using ii = pair;`. – HolyBlackCat Jul 08 '21 at 17:07

2 Answers2

1

From the ref:

void assign (size_type n, const value_type& val);

The new contents are n elements, each initialized to a copy of val.

val

Value to fill the container with. Each of the n elements in the container will be initialized to a copy of this value. Member type value_type is the type of the elements in the container, defined in vector as an alias of its first template parameter (T).

As @user4581301 commented: "vii() constructs a temporary variable that will be used in the assign method and then go out of scope. Fortunately a copy is made of the temporary (assuming the compiler doesn't do some time-saving trickery) so AL isn't left referring to dead space".

gsamaras
  • 71,951
  • 46
  • 188
  • 305
0

In

AL.assign(V, vii());

vii() executes the std::vector default constructor to provide a temporary object to be used as a template (English term, not a C++ template) by std::vector::insert. This temporary will effectively be copied V times, filling AL up with V vectors of pairs, and then it will go out of scope.

user4581301
  • 33,082
  • 7
  • 33
  • 54