I have a problem here: I am to write a function that prints the elements of a vector recursively so no loop is allowed.
I tried this code but it crashes at runtime:
void print(const std::vector<int> ivec, std::vector<int>::const_iterator it) {
if (it == ivec.end())
return;
std::cout << *it++ << std::endl;
print(ivec, it);
}
int main(){
vector<int> v{
5, 7, 77, 23, 10, 81
};
print(v, v.begin());
}
If I run the program I get the assertion dialog!?
void print(const std::vector<int> ivec, std::vector<int>::const_iterator it) {
The ivec
parameter is passed by value. Both of these parameters are passed by value. Passing by value by means that inside the function these are copies of the original parameters.
Your main()
calls this recursive function passing it its vector and the beginning iterator of its vector. However because all parameters are passed by value, each recursive iteration of the function compares the iterator to the end()
of a completely different vector. Undefined behavior.
You obviously forgot to pass the vector by reference. The first parameter to should be const std::vector<int> &ivec
.
Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.
En caso de infracción, por favor [email protected] Eliminar
Déjame decir algunas palabras