int main(){
std::vector<std::string> v = {"test", "tester", "tester"};
for (auto i:v){
if (i == v.back()){
std::cout << "last element" << std::endl;
}
}
}
I am trying to get the if condition to execute only on the last element. I am not sure on how to do this?
at this point i am not trying ot string out the vector elements, i am just interested in checking a vector for the last element, even if other elements contain the same value.
@xismn
that would be comparing a string against an int as size() returns the integer size of the vector. Iterators also bring back the same results of executing from both the second and last element of the vector example, instead of only the last element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main(){
std::vector<std::string> v = {"test", "tester", "tester"};
std::string *last = &v.back();
for (auto i:v){
if (i == v.back())
std::cout << "last element" << std::endl;
if (&i == last)
std::cout << "yes" << std::endl;
}
for (std::vector<std::string>::iterator it = v.begin(); it < v.end(); ++it){
if (*it == v.back())
std::cout << "back" << std::endl;
}
}
i just now figured out i guess what you guys meant.
1 2 3 4 5 6 7 8 9 10 11
int main(){
std::vector<std::string> v = {"test", "tester", "tester"};
for (std::vector<std::string>::iterator it = v.begin(); it < v.end(); ++it){
if (&v.back() == &*it){ //if address of index == address of iterator
std::cout << &v.back() << " == " << &*it;
}
}
}
I switched out this method in the function overload i was intially usng, and now i get an error i am not sure what it means:
Anyway, your error message is clear. obj is const. obj.tokens is const. Iterators to obj.tokens must be const_iterator. You want a non-const iterator, which thus is an error. You don't need a non-const iterator ...
for(std::vector<std::string>::const_iterator it = obj.tokens.begin(); it != obj.tokens.end(); ++it){ // since obj is const you need a const iterator
...
}