Thread: Switching elements in a list

  1. #1
    Registered User
    Join Date
    Sep 2007

    Switching elements in a list


    Is it possible to swap elements in a list? For example, if my list looked like

    list<int> myList = {1, 2, 3, 4} (incorrect syntax, i know)
    Is there some way to switch the 3 and 4 around, how it would then look like {1, 2, 4, 3} ?
    "I don't fail - I succeed at finding things that don't work"
    Website Promotion Techniques

  2. #2
    and the hat of sweating
    Join Date
    Aug 2007
    Toronto, ON
    Did you try the std::swap() function in <algorithm>?
    I think you should be able to just swap the iterators to 2 elements.

  3. #3
    Registered User
    Join Date
    Oct 2005
    But how would you randomly access elements in list? And since you can't randomly access list elements, you'd have to swap iterators, or iter_swap, which you'd have increment/decrement through a tedious process to get where you intend it to be.

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    New Zealand
    What are you wanting to swap item positions for... Are you implementing a sorting algorithm?

    Are the ones you want to swap always next to each other?

    btw You aren't forced to be bound by the notion of swapping when it comes to lists, and indeed it can be better to not attempt to do such things. For example you can achieve the reordering you want by removing 4, and reinserting it between 2 and 3.
    Whatever you do, don't treat a list as though it provides random access.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. circular doubly linked list help
    By gunnerz in forum C++ Programming
    Replies: 5
    Last Post: 04-28-2007, 08:38 PM
  2. Conflicting types of typedef error
    By advocation in forum C++ Programming
    Replies: 4
    Last Post: 03-22-2005, 06:26 PM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. Linked list with two class types within template.
    By SilasP in forum C++ Programming
    Replies: 3
    Last Post: 02-09-2002, 06:13 AM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM