Swapping array elements

Is there a way to swap an element into an array at a specific point. For example i have a string array of {"cat", "dog", "fish"} and i want to swap out "dog" with "mouse". So that the finished string array looks like {"cat", "mouse", "fish"} Is there a way to do that?
animal[1]="mouse";
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string arr[] { "cat", "dog", "fish" } ;
    std::string str = "mouse" ;

    // swap "dog" (arr[1]) with "mouse" (str)
    using std::swap ; // https://en.cppreference.com/w/cpp/algorithm/swap
    swap( arr[1], str ) ;

    std::cout << arr[1] << '\n' // mouse
              << str << '\n' ; // dog

    std::string arr2[] { "red", "green", "blue" } ;

    // swap the contents of the two arrays arr and arr2
    // (note that the two arrays are of the same size)
    swap( arr, arr2 ) ;

    // print the contents of arr after the swap
    for( const auto& s : arr ) std::cout << s << ' ' ; // red green blue
    std::cout << '\n' ;

    // print the contents of arr2 after the swap
    for( const auto& s : arr2 ) std::cout << s << ' ' ; // cat mouse fish
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/9364b0a3d01d45e7
"swap" as you are using it, you are saying 'replace' which is valid in conversational english. swap, to computer programmers, though, means that two values change places and both still exist somewhere. Lastchance gave you the first, JLBorges gave you the second.
Last edited on
Topic archived. No new replies allowed.