2

Why it's not possible to create a pair object in the following way:

pair<int,int> p1 = {0,42}
user1602564
  • 49
  • 1
  • 1
  • 2
  • 1
    Why do you think it's not possible? – sbi Aug 16 '12 at 09:37
  • If you are compiling under Linux, try linking with -std=c++11. Provided you've included the semi colon etc, it should work fine. – Owl Mar 29 '16 at 16:15

2 Answers2

8

in C++03 you should use

std::make_pair(0, 42);

since pair is not simple data-structure. or by calling constructor of pair i.e.

std::pair<int, int> p1(0, 42);

in C++11

pair<int, int> p1 = {0, 42}

is okay.

ForEveR
  • 55,233
  • 2
  • 119
  • 133
4

Initializer list syntax is not allowed in C++03 because std::pair is not an aggregate, therefore the valid way of initializing is a constructor call.

Formal definition from the C++ standard (C++03 8.5.1 §1):

An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).

Please read FAQ for a detailed explanation.

Things are changed in C++11 by introduction of std::initializer_list.

Community
  • 1
  • 1
Andriy
  • 8,486
  • 3
  • 27
  • 51