I have created an iterator, when using it everything works fine; however, when I try to pass it to a function and use it in the same way as before I get the error Violación de segmento ('core' generado)
.
My code goes like this:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Token {
private:
string valor;
public:
Token();
Token(string valor_): valor(valor_) {}
string getValor(){ return valor; }
};
void eval_expresion(vector<Token>::iterator it, vector<Token> tokens){
// cout << it->getValor() << endl;
for(; it != tokens.end(); it++){
cout << it->getValor() << " ";
}
}
int main(){
vector<Token> tokens;
tokens.push_back(Token("var"));
tokens.push_back(Token("="));
tokens.push_back(Token("10"));
vector<Token>::iterator it_tokens;
for(it_tokens = tokens.begin(); it_tokens != tokens.end(); it_tokens++){
Token tk = *it_tokens;
if(tk.getValor() == "var") eval_expresion(it_tokens, tokens);
}
}
It seems strange to me, because if I uncomment the line cout << it->getValor() << endl;
, this shows me the value correctly and as I use the iterator correctly, I use it the same as in the first for
.
Your problem is very simple:
You create a container.
You create an iterator over the container .
You pass a copy of the iterator to the function and
You pass a copy of the container to the function.
That's it: the iterator has been created by a container ... and you intend to use it in a different container (a copy of something is not the same thing as the original):
The solution is as simple as passing the same container from which you create the iterator to the function. For example, by reference: