I am writing this function for merging two vectors in order.
each vector should be in order already before merging, so check that in the beginning.
after that I start to copy two vectors in order, to third vector using loop.
However when I implement this in main function and run this program,
an error pops up saying vector subscript out of range error..... i have been struggling with this more then 10 hours... please help
[code]
#include <iostream>
#include <vector>
using namespace std;
//if vecA or vecB is not sorted, return false
for (int i = 0; i < sizeB && i< sizeA; i++)
{
if ((vecB[i]>vecB[i + 1]) || (vecA[i]>vecA[i + 1]))
{
return false;
}
}
for (int i = 0; i < sizeB; i++)
{
if (vecB[i]>vecB[i + 1])
{
return false;
}
}
//for (int i = 0; i < sizeA; i++)
//{
//if (vecA[i]>vecA[i + 1])
//{
//return false;
//}
//}
//resizing space of vecC to fit all the contents of vecA and vecB
vecC.resize(sizeA + sizeB);
//initializing counts to 0 before start merging
int countA = 0, countB = 0, countC = 0;
//copy copy elements whatever is smaller to vecC from vecA or vecB and increase count that is copied
//untill there one of the vector's elements are all copied.
for (; (countA < sizeA) && (countB < sizeB); countC++)
{
if (vecA[countA] <= vecB[countB])
{
vecC[countC] = vecA[countA];
countA++;
}
else if (vecA[countA] > vecB[countB])
{
vecC[countC] = vecB[countB];
countB++;
}
}
//if there is element left in countA copy all the elements to vecC
while (countA < sizeA)
{
vecC[countC] = vecA[countA];
countA++, countC++;
}
//if there is element left in countB copy all the elements to vecC
while (countB < sizeB)
{
vecC[countC] = vecB[countB];
countB++, countC++;
}
return true;
}
int main()
{
int end;
int sizeA, sizeB;
vector<double> vecA;
vector<double> vecB;
vector<double> vecC;
cout << "please enter sizes of two vectors" << endl << endl;
cout << "Size of vector 1 ";
cin >> sizeA;
cout << endl << "Size of vector 2 ";
cin >> sizeB;
cout << endl;
cout <<endl<< "Please enter values in the second vector";
for (int i = 0; i < sizeB; i++)
{
cout << endl << "Element#" << i+1<< ": ";
cin >> vecB[i];
}
if ((mergeTwoSortedVectors(vecA, vecB, vecC)) == false)
{
cout << "values are not sorted";
}
else
{
cout << endl;
for (int i = 0; i < sizeA + sizeB; i++)
{
cout << vecC[i];
}
}
cin >> end;
}