c++ - Why am I getting this conversion error when I pass a vector by const reference? -
this question has answer here:
here's short program prints out terms of std::vector object. vector passed in const reference efficiency.
#include <iostream> #include <vector> using std::vector; using std::cout; using std::endl; void print_all_terms(const std::vector<int>&); int main() { std::vector<int> sequence_1(4, 100); print_all_terms(sequence_1); return(0); } void print_all_terms(const std::vector<int>& sequence) { (std::vector<int>::iterator = sequence.begin() ; != sequence.end() ; ++it) { std::cout << *it << " "; } std::cout << std::endl; } however, when run program, error:
error: conversion '__gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >' non-scalar type '__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >' requested this caused fact iterator it declared std::vector<int>::iterator, resolves to
__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > > while begin() function returning object of type
__gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > > the difference const in second one. don't see why const should there - yes, variable sequence passed in constant reference, it's reference const, not sequence itself.
you need const_iterator, change loop follows:
for (std::vector<int>::const_iterator = sequence.begin() ; != sequence.end() ; ++it) if have c++11 compiler, can simplify using auto
for (auto = sequence.begin() ; != sequence.end() ; ++it) or can use range range loop available c++11
for (auto & val: sequence) { std::cout << val << " "; }
Comments
Post a Comment