Sorry this may seem an elementary type of error but I am new to programming really need help.
My code is to allow the user to type in values into two arrays(any number of values in both since the arrays are dynamic, he/she specifies the number first.)
When I try to run the code I get a vector subscript out of range error.
What could be the problem please?
Thanks in advance.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
int j = m + n;
vector<int> nums3;
for (int i = 0; i < j; i++)
{
nums3[i] = nums1[i];
nums3[i + m] = nums2[i];
}
}
int main()
{
int m, n;
cout << "What is the size of the array nums1?\n";
cin >> m;
vector<int> nums1;
cout << "Please key in the values in nums1:\n";
for (int i = 0; i < m; i++)
{
cin>>nums1[i];
cout << endl;
}
cout << "What is the size of the array nums2?\n";
cin >> n;
vector<int> nums2;
cout << "Please key in the values in nums1:\n";
for (int k = 0; k < n; k++)
{
cin >> nums2[k];
cout << endl;
}
}
vectors still need internal memory.
you can't just say
vector<int> foo;
foo[100000] = 10;
because making foo, the compiler didn't know you wanted so many locations.
you can tell it this:
vector<int> foo(1000000);
but for your problem the typical solution is to call push-back a lot.
cin >> nums2[k];
should be, then
cin >> temp;
nums1.push_back(temp);
pre-allocating a fixed size or using .reserve to get a big block of memory up front can drastically improve performance for large problems. You can ignore that for now.
I have tried using push_back and the error doesn't come up anywhere, thank you but now the for loop doesn't run.
for example, when I key in the number of values in nums1 as 4 I can only key in one value then it heads to the next, nums2 that is.
And lastly, how can i be able to display what is in nums3?
This would be the perfect time to learn how to use your debugger. That will allow you to step through your code line-by-line, and examine the values of all your variables, so you can figure out what's going on.
#include <iostream>
#include <vector>
int main()
{
std::size_t n ;
std::cout << "what is the size of the array nums1: " ;
std::cin >> n ;
std::vector<int> nums1(n) ; // note: create a vector of size n
// fill the vector with values from stdin
std::cout << "please key in " << n << " values\n" ;
// range-based loop: http://www.stroustrup.com/C++11FAQ.html#forfor( int& v : nums1 ) std::cin >> v ;
std::size_t m ;
std::cout << "what is the size of the array nums2: " ;
std::cin >> m ;
std::vector<int> nums2 ; // note: create an empty vector
// fill the vector with values from stdin
std::cout << "please key in " << m << " values\n" ;
while( nums2.size() < m )
{
int number ;
std::cin >> number ;
// add the number to the end of the vector
nums2.push_back(number) ; // note: push_back
}
}