user1850980
user1850980

Reputation: 1021

Last Element of Vector Changes After Making Copy and Popping from Copy

In C++, I have a function that is supposed to split a vector into its last element and the rest of the vector. However, I make the following observations which I cannot explain:

function(vector<int> indeces){
    // indeces = [1,2,3]
    vector<int> indeces_ = indeces;
    // indeces = [1,2,3] = indeces_
    indeces_.pop_back();
    // indeces = [1,2,3], indeces_ = [1,2]   
    // BUT: *indeces.end() != 3 but some unrelated integer
}

Upvotes: 1

Views: 82

Answers (2)

Ram
Ram

Reputation: 3133

I think you are not using the std::vector class right.

void std::vector<type>::pop_back() deletes the last element in the collection, effectively reducing the container size by one.

The function std::vector<type>::end() returns an iterator that is in this case a pointer pointing to an element past the last element in the collection.

Also, there are a couple of issues with the code you have posted. A function is expected to return a type. If you want to return nothing, then return void.

Upvotes: 0

nvoigt
nvoigt

Reputation: 77294

Your code is wrong. You cannot use end() that way:

Returns an iterator referring to the past-the-end element in the vector container.

The past-the-end element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced.

Upvotes: 2

Related Questions