This is my problem:

getCurves (a);

vector<int> RA(a), SA(a);

I need to determine the size of vector for "RA" and "SA" by using "a" which is a reference parameter that obtained from "getCurves" function.

I will get this error message everytime I compile - "vector subscript out of range".

However, there is not problem if I declare:
vector<int> RA(1000), SA(1000);


So, I wonder why this will happen and why can't I change the size of "RA"and "SA" with "a"?

Can you post something that I can compile? I cannot reproduce your problem with the code given.

# include <iostream>
# include <iomanip>
# include <math.h>
# include <vector>

using namespace std;


void getCurves(int& );

int main()
{
	int a = 0, y = 1;

	getCurves(a);

	vector<float> RA(a);

	cout << "Please key in RA : ";

	for(int i = 1; i <= a; i++)
		cin >> RA[i];

	cout << "RA : " << endl;
	for(int j = 1; j <= a; j++)
		cout << RA[j] << endl;

	system("pause");

}

void getCurves(int& a)
{
	int pass = 0;

	cout << "Plese key in 'a' : ";
	cin >> pass;

	a = pass;
}

It should be something like this. If I key in a = 5, suppose I can key in 5 numbers. However, there will be an error after 4 numbers.

Anyway, I already get it.
Thanks.

for(int i = 1; i <= a; i++)

Vectors are indexed the same way as arrays, using 0 based indexes. You start at 0 and go to N-1:

# include <iostream>
# include <iomanip>
# include <math.h>
# include <vector>

using namespace std;

void getCurves(int& );

int main()
{
    int a = 0, y = 1;

    getCurves(a);

    vector<float> RA(a);

    cout << "Please key in RA : ";

    for(int i = 0; i < a; i++)
        cin >> RA[i];

    cout << "RA : " << endl;
    for(int j = 0; j < a; j++)
        cout << RA[j] << endl;

    system("pause");
}

void getCurves(int& a)
{
    int pass = 0;

    cout << "Plese key in 'a' : ";
    cin >> pass;

    a = pass;
}

The error you were getting was right. There were only 5 slots in the vector, but you were trying to access the 6th. It did not exist and threw and exception.

This article has been dead for over six months. Start a new discussion instead.