簡體   English   中英

在 C++ 中合並 int 和 char 數組

[英]Merge int and char array in c++

按照以下方式將兩個charint數組合並到第三個數組中。


Input:  arr1 = [a, b, c, d]
      
        arr2 = [1, 2, 3, 4]

Output: arr3 = [a1, b2, c3, d4]

這是我之前嘗試過的。我們如何使用指針來做到這一點。 或者不使用指針。 arr3 的數據類型應該是什么。


void mergeArrays(int arr1[], char arr2[], int n1, int n2, datatype* arr3[])
{

    int i = 0, j = 0, k = 0;
 

    // Traverse both array

    while (i<n1 && j < n2){

        

        if (arr1[i] < arr2[j])

            arr3[k++] = arr1[i++];

        else

            arr3[k++] = arr2[j++];

    }
 

    
    while (i < n1)

        arr3[k++] = arr1[i++];
 

    

    while (j < n2)

        arr3[k++] = arr2[j++];
}
 

您仍然在“C”樣式數組方面考慮太多。 您可能想通過https://www.learncpp.com/了解更現代的 C++ 方法。 使用這種方法,您的代碼看起來更像這樣:

#include <stdexcept>
#include <iostream>
#include <vector>
#include <string>

// use std::vector instead of "C" style arrays, they keep track of memory managment AND size of the arrays
// the const's ensure the function cannot modify the input arrays
// the reference (&) ensures the input arrays are not copied.

std::vector<std::string> merge(const std::vector<char>& char_values, const std::vector<int>& int_values)
{
    // check your input, merging doesn't make sense if arrays are not of the same length
    if (int_values.size() != char_values.size()) throw std::invalid_argument("arrays do not have equal size");
    
    std::vector<std::string> merged_array;
    merged_array.reserve(int_values.size());
    
    // use cbegin instead of begin
    // these iterators should constant to not change the input arrays
    auto int_it = int_values.cbegin();
    auto char_it = char_values.cbegin();
    
    for (; int_it != int_values.cend(); ++int_it, ++char_it)
    {
        // *char_it is the character
        // std::to_string converts integer to std::string
        // the + operator merges them togehter 
        // the result is a temporary std::string (not visible to you)
         // emplace_back can efficiently put this temporary into the vector
        merged_array.emplace_back(*char_it + std::to_string(*int_it));
    }

    // by using std::vector you also don't have to use a 3rd char** argument
    // making it much more clear who owns the memory
    // and you can just return an object!
    return merged_array;
}

int main()
{
    std::vector<char> char_values{ 'a', 'b', 'c' };
    std::vector<int> int_values{ 1,2,3 };

    auto merged_values = merge(char_values, int_values);

    // range based for loops are a safe way to loop over vectors
    for (const auto& value : merged_values)
    {
        std::cout << value << "\n";
    }

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM