Home c++ C++: std :: vector.push_back () and classes

C++: std :: vector.push_back () and classes

Author

Date

Category

In your program, I created the Score class. In it, I created a blank constructor, as well as a designer in which the default Na string is unknown .

class score {
  String Name;
  INT SC;
Public:
  Score ();
  Score (Const int & amp; SC, Const String & Amp; Na = "Unknown") {
    This - & gt; Name = Na;
    This - & gt; SC = SC;
  }
};

Next, I want to create a class of class objects that will be filled as you read from a specially harvested file.

using namespace STD;
INT MAIN () {
  ifstream f;
  String Name;
  INT SCORE;
  Vector & lt; Score & GT; v;
  F.Open ("score.txt");
  if ((F.is_open ()) & amp; & amp; (! f.eof ())) {
    F & GT; & gt; Name;
    F & GT; & gt; Score;
    v.push_back (Score, Name);
  }
  F.Close ();
Return 0;
}

At this stage, the compiler issues an error –

& lt; ... & gt; \ main.cpp: 60: error: no Matching Function for Call to 'STD :: vector & lt; score & gt; :: Push_Back (int & amp;, std :: string & amp;) '
     v.push_back (Score, Name);
                ^

I sincerely do not understand what I do wrong and ask to help figure out. Thank you in advance.


Answer 1, Authority 100%

You need to write like this v.push_back (Score (Score, Name));


Answer 2, Authority 200%

Use Emplace_back is more concise and productively. Then you can write as writing initially:

v.emplace_back (score, name);

It will work only in C++ 11 or C++ 14 mode, but now all major compilers are well supporting these standards (but until they turn them on by default, for example, G ++ and Clang ++ require the key -std = C++ 11).

a few more comments:

  • You will not lose anything, replacing Const int & amp; on int – Even the opposite
  • your flow check can be replaced simply on if (f) – there is a conversion to bool , equivalent to call Good ()
  • Instead of Open , you can use the ifstream designer, which accepts the file name, and call Close manually in this example is not necessary, since F immediately comes out of the scope, and the file closes in the destructor
  • Less obvious refinement: If you intend to copy the string transmitted to the constructor, then it is most effectively transmitting it by value, and in the constructor to transfer with rows is a bad idea due to Small String Optimization, and in general Underwater stones here are very much, so I feed this recommendation & lt; _ & lt;

See EFFECTION C++ and EFFECTIVE Modern C++ for details

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions