I would like to learn how to interpret the compilers error results. for edxample:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <string>
#include <vector>
class Deck{
public:
std::vector<int> spades = {1,2,3,4,5,6,7,8,9,10,11,12,13};
void fill_cards(std::vector<int> v){
}
};
int main(){
Deck deck;
for (std::vector<int>::iterator it = deck.spades.begin(); deck.spades.end(); it++){
std::cout << *it << std::endl;
}
}
produces the error:
1 2 3
test.cpp: In function ‘int main()’:
test.cpp:15:79: error: could not convert ‘deck.Deck::spades.std::vector<_Tp, _Alloc>::end<int, std::allocator<int> >()’ from ‘std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}’ to ‘bool’
for (std::vector<int>::iterator it = deck.spades.begin(); deck.spades.end(); it++){
at first it looks like gibberish, but i would like to learn how to interpret the meaning of it.
like the first section: deck.Deck::spades.std::vector<_Tp, _Alloc>::end<int
i know that deck is my object, Deck::spades is my vector, but what does .std::vector<_Tp, _Alloc>::end<int mean?
and in addition to that, i was wondering the actual problem, why does the iterator method have trouble but this method works?
To me it means that the compiler is saying that deck.spades.end() is an iterator when it is expecting a bool. Moreover, the compiler fails to understand how to carry out this conversion from iterator to bool.
EDIT: in your second example, i<deck.spades.size() is a bool which is why it works.
for (std::vector<int>::iterator it = deck.spades.begin(); deck.spades.end(); it++)
the second expression that is deck.spades.end() must be converted to a bool expression that to check whether the loop will iterate. However this type std::vector<int>::iterator has no a conversion function that converts an object of this type to a bool value. And the compiler reports about this situation.
look up the c++11 range based for loop. it makes things like this simple
oh wow, i didnt know this existed. This is pretty much the same as python's for loop then. In that case why would you use the old method? looping a container is most of the reasons for a for loop anyways. normally you want it incremented by one, and normally youo want it from start to end, which makes this new feature a god send.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <string>
#include <vector>
class Deck{
public:
std::vector<int> spades = {1,2,3,4,5,6,7,8,9,10,11,12,13};
void fill_cards(std::vector<int> v){
}
};
int main(){
Deck deck;
for (auto i: deck.spades)
std::cout << i << ' ';
}
This is pretty much the same as python's for loop then
yes
n that case why would you use the old method?
when you need to work on multiple containers in the same loop that might not be of the same type, or if you need to change multiple containers in one loop