Есть ли способ взять два массива int в С++
int * arr1;
int * arr2;
//pretend that in the lines below, we fill these two arrays with different
//int values
а затем объединить их в один более крупный массив, который содержит оба значения массивов?
Есть ли способ взять два массива int в С++
int * arr1;
int * arr2;
//pretend that in the lines below, we fill these two arrays with different
//int values
а затем объединить их в один более крупный массив, который содержит оба значения массивов?
int * result = new int[size1 + size2];
std::copy(arr1, arr1 + size1, result);
std::copy(arr2, arr2 + size2, result + size1);
Просто предположим, что vector
будет работать лучше как динамический массив, а не как указатель
Если вы используете массивы, вам нужно выделить новый массив, достаточно большой для хранения всех значений, а затем скопировать значения в массивы. Это потребует знания размеров массивов и т.д.
Если вы используете std::vector
вместо массивов (что имеет другие преимущества), это становится проще:
std::vector<int> results;
results.reserve(arr1.size() + arr2.size());
results.insert(results.end(), arr1.begin(), arr1.end());
results.insert(results.end(), arr2.begin(), arr2.end());
Другая альтернатива - использовать шаблоны выражений и притворяться, что они объединены (ленивая оценка). Некоторые ссылки (вы можете сделать дополнительный поиск в googling):
http://www10.informatik.uni-erlangen.de/~pflaum/pflaum/ProSeminar/ http://www.altdevblogaday.com/2012/01/23/abusing-c-with-expression-templates/ http://aszt.inf.elte.hu/~gsd/halado_cpp/ch06s06.html
Если вы ищете простоту использования, попробуйте:
#include <iostream>
#include <string>
int main()
{
int arr1[] = {1, 2, 3};
int arr2[] = {3, 4, 6};
std::basic_string<int> s1(arr1, 3);
std::basic_string<int> s2(arr2, 3);
std::basic_string<int> concat(s1 + s2);
for (std::basic_string<int>::const_iterator i(concat.begin());
i != concat.end();
++i)
{
std::cout << *i << " ";
}
std::cout << std::endl;
return 0;
}
Вот решение для того же самого -
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
void Concatenate(char *s1,char *s2)
{
char s[200];
int len1=strlen(s1);
int len2=strlen(s2);
int j;
///Define k to store the values on Kth address Kstart from 0 to len1+len2;
int k=0;
for(j=0;j<len1;j++)
{
s[k]=s1[j];
k++;
}
for(j=0;j<len2;j++)
{
s[k]=s2[j];
k++;
}
///To place a null at the last of the concatenated string to prevent Printing Garbage value;
s[k]='\n';
cout<<s;
}
int main()
{
char s1[100];
char s2[100];
cin.getline(s1,100);
cin.getline(s2,100);
Concatenate(s1,s2);
return 0;
}
Надеюсь, что это поможет.
for (int i = 0; i< arraySize * 2; i++)
{
if (i < aSize)
{
*(array3 + i) = *(array1 + i);
}
else if (i >= arraySize)
{
*(array3 + i) = *(array2 + (i - arraySize));
}
}
Это может помочь вам, оно не требует векторов. У меня была аналогичная проблема в моем классе программирования. Надеюсь, это поможет, потребовалось, чтобы я использовал арифметику указателей. Это предполагает, что array1 и array2 динамически инициализируются размером "aSize"
Учитывая int * arr1 и int * arr2, эта программа объединяет в int * arr3 элементы обоих массивов. К сожалению, на С++ вам нужно знать размеры каждого массива, который вы хотите скопировать. Но это не помеха, чтобы выбрать, сколько элементов вы хотите скопировать из arr1 и сколько из arr2.
#include <iostream>
using namespace std;
int main(){
int temp[] = {1,2,3,4};
int temp2[] = {33,55,22};
int * arr1, * arr2, *arr3;
int size1(4), size2(3); //size1 and size2 is how many elements you
//want to copy from the first and second array. In our case all.
//arr1 = new int[size1]; // optional
//arr2 = new int[size2];
arr1=temp;
arr2=temp2;
arr3 = new int;
//or if you know the size: arr3 = new int[size1+size2];
for(int i=0; i<size1+size2; i++){
if (i<size1)
arr3[i]=arr1[i];
else
arr3[i] = arr2[i-size1];
}
cout<<endl;
for (int i=0; i<size1+size2; i++) {
cout<<arr3[i]<<", ";
}
}