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?
#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( constauto& s : arr ) std::cout << s << ' ' ; // red green blue
std::cout << '\n' ;
// print the contents of arr2 after the swap
for( constauto& s : arr2 ) std::cout << s << ' ' ; // cat mouse fish
std::cout << '\n' ;
}
"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.