为什么我得到这个转换错误,当我通过const引用传递一个向量

Why am I getting this conversion error when I pass a vector by const reference?

本文关键字:引用 一个 const 向量 转换 错误 为什么      更新时间:2023-10-16

下面是一个简短的程序,它打印出std::vector对象的项。为了提高效率,将向量本身作为const引用传入。

#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)
{
  for (std::vector<int>::iterator it = sequence.begin() ;
       it != sequence.end() ;
       ++it) {
    std::cout << *it << " ";
  }
  std::cout << std::endl;
}

然而,当我运行程序时,我得到一个错误:

error: conversion from '__gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >' to non-scalar type '__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >' requested

这是由于将迭代器it声明为std::vector<int>::iterator,其解析为

__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >

begin()函数返回类型为

的对象
__gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >

唯一的区别是第二个中的const。但是我不明白为什么const应该在那里-是的,变量sequence作为常量引用传递进来,但它的引用是const,而不是序列本身。

你需要一个const_iterator,改变for循环如下:

for (std::vector<int>::const_iterator it = sequence.begin() ;
       it != sequence.end() ;    ++it)

如果你有c++ 11编译器,你可以使用auto

来简化它
for (auto it = sequence.begin() ;
           it != sequence.end() ;  ++it)  

或者您可以使用c++11

提供的range for range loop
for (auto & val: sequence)
 {
    std::cout << val << " ";
 }