为什么我得到这个转换错误,当我通过const引用传递一个向量
Why am I getting this conversion error when I pass a vector by const reference?
下面是一个简短的程序,它打印出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 loopfor (auto & val: sequence)
{
std::cout << val << " ";
}
相关文章:
- 引用一个已擦除类型(void*)的指针
- 在 C++ 03 中,如何引用一个被煽动的模板函数的地址
- 如何在C (转换Python代码)中引用一个函数
- C++11是否允许引用一个匿名的临时文件
- 你能取消引用一个整数文本吗
- 指针和引用:一个简单的例子
- 取消引用一个空指针数组
- 在C++中,如果我引用一个具有解除分配析构函数~MyClass的对象,那么超出范围的引用会调用析构函数吗
- 如何初始化boost::any并引用一个对象
- 我如何使一个函数指针引用一个局部变量
- 为什么我不需要解引用一个char指针来输出c风格的字符串?
- 如何引用一个静态函数作为参数传递
- 解引用一个超出边界50%的指针(数组的数组)
- 如何将Java中的开关替换为每个情况引用一个变量的列表?
- 试图引用一个被删除的函数
- 试图引用一个被删除的函数,VS 2015
- 我将如何引用一个自定义库与另一个库在c++
- 引用一个未命名的临时对象(生命周期)
- 为什么函数总是引用一个特定的参数
- "unresolved external symbol"从另一个类引用一个类