vector indexing

This is a discussion on vector indexing within the C++ Programming forums, part of the General Programming Boards category; #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; } ...

  1. #1
    bakaman
    Guest

    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?

  2. #2
    Registered User
    Join Date
    Nov 2002
    Posts
    1,109
    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.

  3. #3
    Registered User
    Join Date
    Feb 2003
    Posts
    28
    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());

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21