【问题标题】:Why am I getting this conversion error when I pass a vector by const reference? [duplicate]当我通过 const 引用传递向量时,为什么会出现此转换错误? [复制]
【发布时间】:2015-07-07 12:41:36
【问题描述】:

这是一个打印出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&lt;int&gt;::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 向量上调用 begin() 时,您会得到一个 const 迭代器,您正试图将其转换为非 const 迭代器,这是不合法的。
  • 在C++11中,写for (int e : sequence) { std::cout &lt;&lt; e &lt;&lt; " "; }
  • @juanchopanza 我认为问题略有不同(OP 已经确定问题与const 有关),这里的答案将是关于vector 接口,以防止更改基础内容。跨度>

标签: c++ vector types


【解决方案1】:

你需要一个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 循环

for (auto & val: sequence)
 {
    std::cout << val << " ";
 }

【讨论】:

  • 或者更好,auto
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
  • 1970-01-01
  • 2014-01-13
  • 1970-01-01
  • 1970-01-01
  • 2010-11-26
  • 1970-01-01
相关资源
最近更新 更多