user3288091
user3288091

Reputation: 57

Find Last Defined Element in Vector C++

I'm trying to get the last defined element in a C++ vector, but both vector::capacity and vector::size are just giving me the max size. For example:

int main() {
     char* array = new char[MAX_SIZE]; //MAX_SIZE is a const int equaling 100
     std::cout << "Enter in a number: ";
     std::cin >> array;
     std::vector<char> cVector;
     cVector.reserve(MAX_SIZE); 
     cVector.assign(array, array + MAX_SIZE);
     for (std::vector<char>::const_iterator i = cVector.begin(); i != cVector.end(); ++i) 
     {
          std::cout << *i;
     }
     std::cout << std::endl;
     std::cout << "Size: " << cVector.size() << std::endl;
     std::cout << "Actual size: " << cVector.capacity() << std::endl;
}

Sample Output:

Enter in a number: 55
55
Size: 100
Actual size: 100 [Should say 2]

I've tried using vector::end() and similar methods, but there's no way for me to get the index of the last element.

Upvotes: 0

Views: 122

Answers (2)

bereal
bereal

Reputation: 34292

When you call reserve(MAX_SIZE), you change the capacity, so the output 100 is what it should be. That loop where you print out the values, actually iterates all 100 times, but all the remaining chars are \0, so std::cout interprets those pointers as empty strings. Here is a slightly modified version that create a proper vector, so vector.back() will point to the last element and vector.end() to the next position in memory.

int main() {
    std::string s;
    std::cout << "Enter in a number: ";
    std::cin >> s;
    std::vector<char> cVector;
    cVector.reserve(MAX_SIZE);
    cVector.assign(&s[0], &s[0]+s.size());
    for (std::vector<char>::const_iterator i = cVector.begin(); 
         i != cVector.end(); ++i)
    {
        std::cout << *i;
    }
    std::cout << std::endl;
    std::cout << "Size: " << cVector.size() << std::endl;
    std::cout << "Actual size: " << cVector.capacity() << std::endl;
}

UPDATE: Note that I used std::string only to make it more C++-ish. You can keep using char[], just you need to replace your original assignment with:

cVector.assign(array, array + strlen(array));

Upvotes: 2

Thomas
Thomas

Reputation: 182000

size() gives the length of the vector (the number of elements actually in it, not the number of elements that it can currently fit). You're seeing the same number because you call assign(array, array + MAX_SIZE) on the vector, which will obviously fill it with MAX_SIZE elements.

Upvotes: 1

Related Questions