-
vector indexing
#include<iostream.h>
#include<apstring.h>
#include<apvector.h>
apstring ArrayToString(apvector<char> &, int, int);
void fillArray(apvector<char> &);
int main()
{
apvector<char> A;
fillArray(A);
return 0;
}
void fillArray(apvector<char> & A)
{
int howMany, start, end;
char letter;
cout <<"How many letters do you want this array to be?";
cin>>howMany;
A.resize(howMany);
for(int loop= 0; loop < howMany; loop++)
{
cout <<"Enter a letter?";
cin >>letter;
A[loop]=letter;
}
cout <<endl;
cout <<"Where do you want to start?";
cin >>start;
cout <<"Where do you want to end?";
cin>> end;
ArrayToString(A, A[start], A[end]); //problems here
}
apstring ArrayToString(apvector<char> & A, int start, int end)
{
apstring word;
for(int loop = start; loop <= end; loop++)
{
word+=A[loop];
}
cout <<word;
return word;
}
everytime i try to execute this code, i get an illegal vector index and i cant find it. can anyone help me spot it?
-
use code tags.
Code:
ArrayToString(A, start, end);
you need to pass it start and end, not A[start] and A[end]. The way you were passing it to the fxn, since the parameters ask for ints, they were passing the ascii value of the chars, and that was giving you the illegal vector index. your array was an array of chars, and you passed the chars in to a fxn that asked for ints.
-
One thing, to convert a vector<char> to a string:
Code:
std::string myString(myVector.begin(), myVector.end());
// or on an empty string:
myString.insert(myString.begin(), myVector.begin(), myVector.end());
And the std::string to std::vector<char> works just the same:
Code:
std::vector<char> myVector(myString.begin(), myString.end());
// or on an empty vector<char>
myVector.insert(myVector.begin(), myString.begin(), myString.end());