How to get the index of the smallest element in a vector?How do you set, clear, and toggle a single bit?Obtain an index into a vector using IteratorsHow do I iterate over the words of a string?How to find out if an item is present in a std::vector?How do I erase an element from std::vector<> by index?What is the easiest way to initialize a std::vector with hardcoded elements?Appending a vector to a vectorC++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?How to get std::vector pointer to the raw data?Searching a portion of vector in c++

Can someone publish a story that happened to you?

What causes platform events to fail to be published and should I cater for failed platform event creations?

On The Origin of Dissonant Chords

How did Captain America manage to do this?

Do I have an "anti-research" personality?

What is the smallest unit of eos?

Why didn't the Space Shuttle bounce back into space as many times as possible so as to lose a lot of kinetic energy up there?

How can Republicans who favour free markets, consistently express anger when they don't like the outcome of that choice?

Re-entry to Germany after vacation using blue card

"Hidden" theta-term in Hamiltonian formulation of Yang-Mills theory

Retract an already submitted recommendation letter (written for an undergrad student)

A ​Note ​on ​N!

Critique of timeline aesthetic

Coordinate my way to the name of the (video) game

Is Diceware more secure than a long passphrase?

Two field separators (colon and space) in awk

Did the BCPL programming language support floats?

Don’t seats that recline flat defeat the purpose of having seatbelts?

What happens to Mjolnir (Thor's hammer) at the end of Endgame?

Are there physical dangers to preparing a prepared piano?

How to stop co-workers from teasing me because I know Russian?

How can I print the prosodic symbols in LaTeX?

Check if a string is entirely made of the same substring

Why does nature favour the Laplacian?



How to get the index of the smallest element in a vector?


How do you set, clear, and toggle a single bit?Obtain an index into a vector using IteratorsHow do I iterate over the words of a string?How to find out if an item is present in a std::vector?How do I erase an element from std::vector<> by index?What is the easiest way to initialize a std::vector with hardcoded elements?Appending a vector to a vectorC++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?How to get std::vector pointer to the raw data?Searching a portion of vector in c++






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















I want to know which element of vector is the minimum, but min_element returns an iterator to the element. So I tried this:



vector<int> vec = 4,5,0,1,2,3 ;
int min_element_index = min_element(vec.begin(), vec.end()) - vec.begin();


However, I'm unsure this will always work. I don't know how vectors are stored in memory, and I'm worried this will break when I use push_back.










share|improve this question



















  • 1





    I'm not sure it will always work .Are vector elements stored continuously ?

    – M12421K
    Mar 22 at 17:29






  • 1





    Vector elements are stored continuously in memory. But you don't need to care unless you use vector::data which most of the time you shouldn't do anyway.

    – Jabberwocky
    Mar 22 at 17:30


















2















I want to know which element of vector is the minimum, but min_element returns an iterator to the element. So I tried this:



vector<int> vec = 4,5,0,1,2,3 ;
int min_element_index = min_element(vec.begin(), vec.end()) - vec.begin();


However, I'm unsure this will always work. I don't know how vectors are stored in memory, and I'm worried this will break when I use push_back.










share|improve this question



















  • 1





    I'm not sure it will always work .Are vector elements stored continuously ?

    – M12421K
    Mar 22 at 17:29






  • 1





    Vector elements are stored continuously in memory. But you don't need to care unless you use vector::data which most of the time you shouldn't do anyway.

    – Jabberwocky
    Mar 22 at 17:30














2












2








2








I want to know which element of vector is the minimum, but min_element returns an iterator to the element. So I tried this:



vector<int> vec = 4,5,0,1,2,3 ;
int min_element_index = min_element(vec.begin(), vec.end()) - vec.begin();


However, I'm unsure this will always work. I don't know how vectors are stored in memory, and I'm worried this will break when I use push_back.










share|improve this question
















I want to know which element of vector is the minimum, but min_element returns an iterator to the element. So I tried this:



vector<int> vec = 4,5,0,1,2,3 ;
int min_element_index = min_element(vec.begin(), vec.end()) - vec.begin();


However, I'm unsure this will always work. I don't know how vectors are stored in memory, and I'm worried this will break when I use push_back.







c++ vector






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 at 17:51









NathanOliver

100k16139221




100k16139221










asked Mar 22 at 17:23









M12421KM12421K

167




167







  • 1





    I'm not sure it will always work .Are vector elements stored continuously ?

    – M12421K
    Mar 22 at 17:29






  • 1





    Vector elements are stored continuously in memory. But you don't need to care unless you use vector::data which most of the time you shouldn't do anyway.

    – Jabberwocky
    Mar 22 at 17:30













  • 1





    I'm not sure it will always work .Are vector elements stored continuously ?

    – M12421K
    Mar 22 at 17:29






  • 1





    Vector elements are stored continuously in memory. But you don't need to care unless you use vector::data which most of the time you shouldn't do anyway.

    – Jabberwocky
    Mar 22 at 17:30








1




1





I'm not sure it will always work .Are vector elements stored continuously ?

– M12421K
Mar 22 at 17:29





I'm not sure it will always work .Are vector elements stored continuously ?

– M12421K
Mar 22 at 17:29




1




1





Vector elements are stored continuously in memory. But you don't need to care unless you use vector::data which most of the time you shouldn't do anyway.

– Jabberwocky
Mar 22 at 17:30






Vector elements are stored continuously in memory. But you don't need to care unless you use vector::data which most of the time you shouldn't do anyway.

– Jabberwocky
Mar 22 at 17:30













2 Answers
2






active

oldest

votes


















10














You can also do this:



std::vector<int>::iterator it = std::min_element(std::begin(vec), std::end(vec));
std::cout << "index of smallest element: " << std::distance(std::begin(vec), it);


or even simpler:



auto it = std::min_element(std::begin(vec), std::end(vec));
std::cout << "index of smallest element: " << std::distance(std::begin(vec), it);


or:



std::cout << "index of smallest element: " <<
std::distance(std::begin(v), std::min_element(std::begin(v), std::end(v)))





share|improve this answer




















  • 4





    I like this answer the most since it is more generic and will work with non random access containers as well.

    – NathanOliver
    Mar 22 at 17:38


















3














Vector members are guaranteed to be stored in contiguous memory, which doesn't really matter here.



The vector iterators are random access iterators, so subtracting vector iterators is well defined (This will always work with a standards compliant std::vector)



To convert a vector iterator into a pointer, you can do &*(vector-iterator), but there is no reason to here.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55304846%2fhow-to-get-the-index-of-the-smallest-element-in-a-vector%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    10














    You can also do this:



    std::vector<int>::iterator it = std::min_element(std::begin(vec), std::end(vec));
    std::cout << "index of smallest element: " << std::distance(std::begin(vec), it);


    or even simpler:



    auto it = std::min_element(std::begin(vec), std::end(vec));
    std::cout << "index of smallest element: " << std::distance(std::begin(vec), it);


    or:



    std::cout << "index of smallest element: " <<
    std::distance(std::begin(v), std::min_element(std::begin(v), std::end(v)))





    share|improve this answer




















    • 4





      I like this answer the most since it is more generic and will work with non random access containers as well.

      – NathanOliver
      Mar 22 at 17:38















    10














    You can also do this:



    std::vector<int>::iterator it = std::min_element(std::begin(vec), std::end(vec));
    std::cout << "index of smallest element: " << std::distance(std::begin(vec), it);


    or even simpler:



    auto it = std::min_element(std::begin(vec), std::end(vec));
    std::cout << "index of smallest element: " << std::distance(std::begin(vec), it);


    or:



    std::cout << "index of smallest element: " <<
    std::distance(std::begin(v), std::min_element(std::begin(v), std::end(v)))





    share|improve this answer




















    • 4





      I like this answer the most since it is more generic and will work with non random access containers as well.

      – NathanOliver
      Mar 22 at 17:38













    10












    10








    10







    You can also do this:



    std::vector<int>::iterator it = std::min_element(std::begin(vec), std::end(vec));
    std::cout << "index of smallest element: " << std::distance(std::begin(vec), it);


    or even simpler:



    auto it = std::min_element(std::begin(vec), std::end(vec));
    std::cout << "index of smallest element: " << std::distance(std::begin(vec), it);


    or:



    std::cout << "index of smallest element: " <<
    std::distance(std::begin(v), std::min_element(std::begin(v), std::end(v)))





    share|improve this answer















    You can also do this:



    std::vector<int>::iterator it = std::min_element(std::begin(vec), std::end(vec));
    std::cout << "index of smallest element: " << std::distance(std::begin(vec), it);


    or even simpler:



    auto it = std::min_element(std::begin(vec), std::end(vec));
    std::cout << "index of smallest element: " << std::distance(std::begin(vec), it);


    or:



    std::cout << "index of smallest element: " <<
    std::distance(std::begin(v), std::min_element(std::begin(v), std::end(v)))






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 22 at 17:47

























    answered Mar 22 at 17:36









    JabberwockyJabberwocky

    28.5k103875




    28.5k103875







    • 4





      I like this answer the most since it is more generic and will work with non random access containers as well.

      – NathanOliver
      Mar 22 at 17:38












    • 4





      I like this answer the most since it is more generic and will work with non random access containers as well.

      – NathanOliver
      Mar 22 at 17:38







    4




    4





    I like this answer the most since it is more generic and will work with non random access containers as well.

    – NathanOliver
    Mar 22 at 17:38





    I like this answer the most since it is more generic and will work with non random access containers as well.

    – NathanOliver
    Mar 22 at 17:38













    3














    Vector members are guaranteed to be stored in contiguous memory, which doesn't really matter here.



    The vector iterators are random access iterators, so subtracting vector iterators is well defined (This will always work with a standards compliant std::vector)



    To convert a vector iterator into a pointer, you can do &*(vector-iterator), but there is no reason to here.






    share|improve this answer



























      3














      Vector members are guaranteed to be stored in contiguous memory, which doesn't really matter here.



      The vector iterators are random access iterators, so subtracting vector iterators is well defined (This will always work with a standards compliant std::vector)



      To convert a vector iterator into a pointer, you can do &*(vector-iterator), but there is no reason to here.






      share|improve this answer

























        3












        3








        3







        Vector members are guaranteed to be stored in contiguous memory, which doesn't really matter here.



        The vector iterators are random access iterators, so subtracting vector iterators is well defined (This will always work with a standards compliant std::vector)



        To convert a vector iterator into a pointer, you can do &*(vector-iterator), but there is no reason to here.






        share|improve this answer













        Vector members are guaranteed to be stored in contiguous memory, which doesn't really matter here.



        The vector iterators are random access iterators, so subtracting vector iterators is well defined (This will always work with a standards compliant std::vector)



        To convert a vector iterator into a pointer, you can do &*(vector-iterator), but there is no reason to here.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 22 at 17:35









        ArtyerArtyer

        5,898829




        5,898829



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55304846%2fhow-to-get-the-index-of-the-smallest-element-in-a-vector%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해