今天在做读入一组整数并把它们存入一个vector对象,要求先输出第一个和最后一个元素的和,接着输出第二个和倒数第二个元素的和,以此类推。
下面是我的程序:
#include<iostream>
#include<vector>
using namespace std;
int main(void)
{
vector<int> ivec;
int num;
cout<<"请输入你的整数,按Crtl+d退出:";
while(cin>>num)
ivec.push_back(num);
if(ivec.empty())
{
cout<<endl<<"没有数据,直接退出!"<<endl;
return -1;
}
cout<<endl<<"输出结果:";
for(decltype(ivec.size()) beg = 0,decltype(ivec.size()) end =
ivec.size() - 1;beg<=end;beg++,end--)
cout<<ivec[beg]+ivec[end]<<" ";
cout<<endl;
return 0;
}
但是编译的时候却报错了,下面是报错打印:
p3_20.cpp: In function ‘int main()’:
p3_20.cpp:14:36: error: expected unqualified-id before ‘decltype’
for(decltype(ivec.size()) beg = 0,decltype(ivec.size()) end =
^
p3_20.cpp:14:36: error: expected ‘;’ before ‘decltype’
p3_20.cpp:15:27: error: expected ‘)’ before ‘;’ token
ivec.size() - 1;beg<=end;beg++,end--)
^
p3_20.cpp:15:28: error: ‘beg’ was not declared in this scope
ivec.size() - 1;beg<=end;beg++,end--)
^
p3_20.cpp:15:37: error: no post-decrement operator for type
ivec.size() - 1;beg<=end;beg++,end--)
^
因为自己是个菜鸡,想了一会才想到是因为在一条语句(一个;分号)中重复声明同一种类型
for(decltype(ivec.size()) beg = 0,decltype(ivec.size()) end = ivec.size() - 1;beg<=end;beg++,end--)
类似于这样 int i,int j;
去掉后面的decltype就可以了。