how to merge string array in C++
To merge string arrays in C++, you can use the std::copy()
function along with the std::back_inserter()
iterator. Here are the steps to do it:
- First, include the necessary header file:
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>
- Declare and initialize the string arrays that you want to merge:
std::string arr1[] = {"Hello", "World"};
std::string arr2[] = {"How", "are", "you"};
- Calculate the sizes of the arrays:
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
- Create a new vector to hold the merged result:
std::vector<std::string> mergedArray;
- Use the
std::copy()
function along with thestd::back_inserter()
iterator to merge the arrays:
std::copy(arr1, arr1 + size1, std::back_inserter(mergedArray));
std::copy(arr2, arr2 + size2, std::back_inserter(mergedArray));
- Now, the
mergedArray
vector contains the merged result.
Here's the complete code example:
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>
int main() {
std::string arr1[] = {"Hello", "World"};
std::string arr2[] = {"How", "are", "you"};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
std::vector<std::string> mergedArray;
std::copy(arr1, arr1 + size1, std::back_inserter(mergedArray));
std::copy(arr2, arr2 + size2, std::back_inserter(mergedArray));
// mergedArray now contains the merged result
}
By using the std::copy()
function and the std::back_inserter()
iterator, you can easily merge string arrays in C++.