Partial vector swapping.

This is a discussion on Partial vector swapping. within the C++ Programming forums, part of the General Programming Boards category; I have two vectors of ints. I need to cut each of them at some arbitrary point and swap the ...

  1. #1
    Registered User
    Join Date
    Aug 2006
    Posts
    43

    Partial vector swapping.

    I have two vectors of ints. I need to cut each of them at some arbitrary point and swap the last half of each. So, if I have:
    Code:
    a = {1, 2, 3, 4, 5, 6}
    b = {7, 8, 9, 10, 11, 12}
    and I swap at the middle, the resulting vectors would be:
    Code:
    a = {1, 2, 3, 10, 11, 12}
    b = {7, 8, 9, 4, 5, 6}
    Now, I could iterate through them and perform the swap to a temporary vector, but I was wondering if there was a function in the STL that would do this for me?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,786
    There is the std::swap_ranges() standard generic algorithm that you can use, e.g.,

    Assuming that the vectors are of equal length:
    Code:
    const std::vector<int>::size_type mid = vec1.size() / 2;
    std::swap_ranges(vec1.begin() + mid, vec1.end(), vec2.begin() + mid);
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. UDP socket partial reading
    By mynickmynick in forum Networking/Device Communication
    Replies: 0
    Last Post: 03-25-2009, 11:43 AM
  2. Why do I get partial web-pages with recv?
    By hardi in forum Networking/Device Communication
    Replies: 11
    Last Post: 12-28-2006, 01:50 PM
  3. partial serialize/deserialize a structure
    By George2 in forum C Programming
    Replies: 2
    Last Post: 09-28-2006, 12:40 AM
  4. partial string matching
    By bazzano in forum C Programming
    Replies: 1
    Last Post: 10-09-2005, 01:52 AM
  5. Partial Specialization error?
    By cboard_member in forum C++ Programming
    Replies: 10
    Last Post: 09-05-2005, 04:23 AM

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