CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 15
  1. #1
    Join Date
    May 2018
    Posts
    158

    struct to vector

    I have to allocate vector with several elements of 'point' type, where its values are collected by cin command.

    I have this structure:

    Code:
    struct point {
       int x;
       int y;
    };
    
    point temp;
    cout << values;
    cin >> temp.x >> temp.y;
    
    vector<point> pp;
    pp.pushback(temp);
    it's right way to make it?
    Can I use different way, e.g. by initialization list? How?

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: struct to vector

    Yes. it looks OK.
    Didn't you test this code?
    Victor Nijegorodov

  3. #3
    Join Date
    May 2018
    Posts
    158

    Re: struct to vector

    Quote Originally Posted by VictorN View Post
    Yes. it looks OK.
    Didn't you test this code?
    Yes; I did but I was interesting to method to make it and if It exists another way, like initialization lists which I don't remember.

  4. #4
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: struct to vector

    If you tested the code, you would have found out that you have a typo on this line:
    Code:
    pp.pushback(temp);
    It should have been:
    Code:
    pp.push_back(temp);
    Quote Originally Posted by zio_mangrovia
    Yes; I did but I was interesting to method to make it and if It exists another way, like initialization lists which I don't remember.
    You're probably going to use a loop, so what you did seems reasonable since you would push_back in the loop. But in the particular example you have, it is true that you could have written:
    Code:
    vector<point> pp{temp};
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  5. #5
    Join Date
    May 2018
    Posts
    158

    Re: struct to vector

    here, I made a mistake to type "pushback".


    vector<point> pp{temp}
    I don't remember, this statement defines pp as vector of 'point' struct elements and it uses copy constructor to copy temp to vector element?

  6. #6
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: struct to vector

    There are a couple of other options:

    If you don't need to use temp after the vector push_back, then you could use move semantics. However, as temp just has two int members it's probably not worth it in this case.

    You could extract to 2 temp ints (rather than a avriable of type point) and then use .emplace_back() to construct and insert a new point into the vector - but again because of the size of the struct, it's probably not worth it.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  7. #7
    Join Date
    May 2018
    Posts
    158

    Re: struct to vector

    Quote Originally Posted by 2kaud View Post
    If you don't need to use temp after the vector push_back, then you could use move semantics.
    What means move semantics?

  8. #8
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: struct to vector

    Victor Nijegorodov

  9. #9
    Join Date
    May 2018
    Posts
    158

    Re: struct to vector

    Thanks for your references.
    About this code
    Code:
    vector<point> pp{temp}
    It uses the copy constructor ?

  10. #10
    Join Date
    Feb 2017
    Posts
    677

    Re: struct to vector

    Quote Originally Posted by zio_mangrovia View Post
    About this code
    Code:
    vector<point> pp{temp}
    It uses the copy constructor ?
    It does and I'd say the copy constructor gets called twice. The code is equivalent to doing,

    Code:
    vector<point> pp = {temp};
    The curly brackets {} mean that first an initializer list containing a copy of temp is created and this involves a call to the copy constructor of temp. Then the temp copy in the initializer list is copied again into pp and that means yet another copy constructor call.
    Last edited by wolle; April 10th, 2019 at 02:25 AM.

  11. #11
    Join Date
    Feb 2017
    Posts
    677

    Re: struct to vector

    Quote Originally Posted by 2kaud View Post
    You could extract to 2 temp ints (rather than a avriable of type point) and then use .emplace_back() to construct and insert a new point into the vector - but again because of the size of the struct, it's probably not worth it.
    Not that it matters much but the OP could still use the temp variable as two temporary ints in a call to emplace_back(). It would look like this,

    Code:
    pp.emplace_back(temp.x, temp.y).
    This would require a matching point constructor and I suggest this,

    Code:
    struct point {
        point(int a, int b) : x(a), y(b) {} // constructor taking two ints
    
        point() = default; // must be explicitly declared to be present due to the existence of the above constructor
    
        int x;
        int y;
    };
    Now the two parameters of the pp.emplace_back(temp.x, temp.y) call will be moved by way of move semantics and used to instantiate a point variable at the proper place inside the pp vector by way of a call to the point(int a, int b) constructor. This, I think, is the best one can do with move semantics. It means one call to a constructor of point.

    Any of these alternatives,

    Code:
    pp.push_back(temp);
    
    pp.emplace_back(temp);
    also means one call to a constructor of point, but it will be the copy constructor.
    Last edited by wolle; April 10th, 2019 at 03:52 AM.

  12. #12
    Join Date
    Feb 2017
    Posts
    677

    Re: struct to vector

    Quote Originally Posted by zio_mangrovia View Post
    Thanks for your references.
    Move semantics was introduced to make copying cheaper and this is important because C++ traditionally prefers it over so called reference semantics (that many other languages prefer such as say Java).

    I've found that it's often the case that move semantics doesn't make code more efficient. It merely allows you to make copies without paying the full price but you can as well accomplish the same by avoiding those copies in the first place. One common strategy for that is to use reference semantics. It comes natural if you do object oriented programming and it's well supported by C++ in the form of so called smart pointers such as std::shared_ptr. They work well with all STL containers including std::vector.

    So as application programmer I don't feel the need to bother much with move semantics and it has been added to C++ in such a way that one shouldn't have to, at least that's my impression.

    In this case the best performance measure probably is to prevent the vector from making relocations while being populated. It can be done by reserving space initially with a call to reserve(). One can always remove excessive space afterwards with shrink_to_fit() if nothing more is to be added later.
    Last edited by wolle; April 10th, 2019 at 04:35 AM.

  13. #13
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: struct to vector

    move was brought in primarily to stop the unnecessary copying of temporaries to much improve performance - and is something you definitely need to know about if you do much template coding or write new classes that use dynamic memory etc etc. unique_ptr, shared_ptr et all wouldn't be possible without it - we'd just have the old broken auto_ptr. Any function that involves copying of parameters should be considered for also move semantics.

    Also, the recommended way to pass say a string and save its contents in a class constructor used to be:

    Code:
    class myc
    {
        myc(const std::string& s) : str(s) {}
    ...
    std::string str;
    };
    it's now (see Meyers):

    Code:
    class myc
    {
        myc(std::string s) : str(std::move(s)) {}
    ...
    std::string str;
    };
    using pass-by-value and then an initialisation using move semantics and not copy.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  14. #14
    Join Date
    Feb 2017
    Posts
    677

    Re: struct to vector

    Quote Originally Posted by 2kaud View Post
    Also, the recommended way to pass say a string and save its contents in a class constructor used to be:
    ...
    it's now (see Meyers):
    ...
    using pass-by-value and then an initialisation using move semantics and not copy.
    It's item 41 in Effective Modern C++ right?

    The string passing case is an example that ends with a general advice and that's to consider pass by value under certain circumstances. Then Meyers spend like 10 pages to present exactly what should be considered so it's not exactly clean-cut.

    The C++ Core Guidelines document by Stroustrup and Sutter is more to the point,

    https://github.com/isocpp/CppCoreGui...eGuidelines.md

    Please have a look at F.15 and F.16. The advice is the same as before the introduction of move semantics namely to pass a string by const_ref.

    That's what all three C++ top gurus think about it. I cannot find any recommendation to pass a string (or anything equivalent) by value?

    I'm not saying move semantics should be ignored but there's no reason to be overly bothered with it during "normal" application programming.
    Last edited by wolle; April 10th, 2019 at 07:42 AM.

  15. #15
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: struct to vector

    See also https://www.bfilipek.com/2018/08/ini...ng-member.html

    PS. Unless there's a good reason I don't like/use value + move, I prefer const ref + copy.

    Code:
    class myc
    {
        myc(const std::string& s) : str(s) {}
        myc(std::string&& s) : str(std::move(s)) {}
    ...
    std::string str;
    };
    re passing string. There's also a point of view that you pass by string_view.

    However, I think this thread is now veering away from the original point!
    Last edited by 2kaud; April 10th, 2019 at 09:23 AM. Reason: PS
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured