I have the following function that is supposed to compute the sum of all elements of a vector :
double arraySum(vector<double> const &v) {
double initial_sum = 0.0;
return accumulate(v.begin(), v.end(), initial_sum);
}
From antoher side, if I have the following list and I want to delete the last string, I do :
param_chain_A = {"wm", "wde", "wb", "w0", "wa", "h", "ns", "s8", "gamma", "A_IA", "n_IA", "B_IA", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "b10", "b11"};
if (model == "S") {
param_chain_A.erase(param_chain_A.end()-1);
}
As you can see, in the first example, I used v.end()
for the last element of a vector and param_chain_A.end()-1
for the last element of a list.
I just want to understand better how to identify the last element for a vector and a list with keywords .end()
.
From this link, it is said that :
"You're trying to count down j to zero, and imageDataVector.end() - 0 is not a valid iterator. In the standard C++ library containers, the end iterator points one past the last element, not at the last element."
So my question is simple : is there a difference between accessing to the last element (for eventually to remove it) of a vector and last element of a list ?
If no, how to handle in both case this kind of stuff (removing the last element)
I have a third example where I want to extract a subvector of an initial vector :
// Slice for arrays like python syntax
vector<double> slice(vector<double> const &v, int m, int n)
{
vector<double>::const_iterator first = v.begin() + m;
vector<double>::const_iterator last = v.begin() + n;
vector<double> vec(first, last);
return vec;
}
In this case, I extract the vector beginning at the m+1 element
up to including n+1 element
of vector v
, don't I ? Here, I don't use .end()
.
I have to indicate that I would like to get a std-c++11
convention (if possible).
Any clarification/explanation is welcome.
PS: I saw that there was .rbegin()
iterator to access directly to the last element, but is it a problem to use std-c++14
instead of std-c++11
versions, I mean, for a basic scientific code (I don't push too far away the "object" logical of C++ in my code, simply using a class with classicla attributes and methods).
Aucun commentaire:
Enregistrer un commentaire