Replace elements in vector

This is a discussion on Replace elements in vector within the C++ Programming forums, part of the General Programming Boards category; Code: std::vector<int> PutNumbers; PutNumbers.push_back(1); PutNumbers.push_back(2); PutNumbers.push_back(3); //Result PutNumbers[0] = 1; PutNumbers[1] = 2; PutNumbers[2] = 3; I have this code ...

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    59

    Replace elements in vector

    Code:
    std::vector<int> PutNumbers;
    
    PutNumbers.push_back(1);
    PutNumbers.push_back(2);
    PutNumbers.push_back(3);
    
    //Result
    PutNumbers[0] = 1;
    PutNumbers[1] = 2;
    PutNumbers[2] = 3;
    I have this code above where I push_back numbers to 3 elements.
    I am reading these numbers from a file but when I will read the fourth number wich could be 4 I want to replace the vector so it will look like below.
    I know I can do this manually by iterate trough the elements etc.. This is not a problem.
    But I wonder if there is any function for this for the std::vector to easy achive this. I have searched around but havn&#180;t found anything about that subject.
    Thank You!

    Code:
    PutNumbers.push_back(4);
    
    //Result
    PutNumbers[0] = 2;
    PutNumbers[1] = 3;
    PutNumbers[2] = 4;

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,270
    Before push_back(), check if the size is equal to 3. If so, pop_front() first. std::deque would likely be better than std::vector for this, actually.

    EDIT:
    Oops, std::vector does not have pop_front(), so you'll have to just use erase() if you do not use a std::deque instead.
    Last edited by laserlight; 11-18-2008 at 12:39 PM.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Oct 2008
    Posts
    59
    Yes this is a good id&#233;a to check the size also.
    Thanks laserlight, I will check this out.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. vector search and replace
    By rahulsk1947 in forum C++ Programming
    Replies: 6
    Last Post: 06-04-2009, 10:13 PM
  2. How can i made vectors measuring program in DevC++
    By flame82 in forum C Programming
    Replies: 1
    Last Post: 05-07-2008, 03:05 PM
  3. Vector class
    By Desolation in forum C++ Programming
    Replies: 2
    Last Post: 05-12-2007, 06:44 PM
  4. my vector class..easy dynamic arrays
    By nextus in forum C++ Programming
    Replies: 5
    Last Post: 02-03-2003, 10:14 AM
  5. Operators for 3D Vector Mathematics
    By Anarchist in forum C++ Programming
    Replies: 10
    Last Post: 01-31-2003, 07:33 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21