//讀一組整數到vector對象,計算首尾配對元素的和並輸出
//使用迭代器訪問vector中的元素
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int> ivec;
int ival;
//讀入數據到vector對象
cout<<"Enter numbers(Ctrl+Z to end):"<<endl;
while(cin>>ival)
ivec.push_back(ival);
//計算首尾配對元素的和並輸出
if(ivec.size()==0){
cout<<"No element?!"<<endl;
return -1;
}
cout<<"Sum of each pair of counterpart element in the vector:"
<<endl;
vector<int>::size_type cnt=0;
for(vector<int>::iterator first=ivec.begin(),last = ivec.end()-1;first<last;++first,--last){
cout<<*first+*last<<"/t";
++cnt;
if(cnt %6 ==0) //每行輸出六個和
cout<<endl;
}
if(first==last) //提示居中元素沒有求和
cout<<endl
<<"The center element is not been summed"
<<"and its value is"
<<*first<<endl;
return 0;
}
在ubuntu下用g++編譯會出現如下錯誤:
/mywork/mytest/iterator/main.cpp:88: error: name lookup of 'first' changed for ISO 'for' scoping [-fpermissive]
/mywork/mytest/iterator/main.cpp:88: (if you use '-fpermissive' G++ will accept your code)
錯誤的原因: for循環中在初始化時同時定義的變量的作用域範圍的一個問題。 ISO/ANSI C++ 把在此定義的變量的作用域範圍限定在 for 循環體內,也就是說,在循環體之外這個變量是無效的。但是編譯的時候可以加參數-fpermissive,就沒有問題了。如果不加這個參數,直接把for中定義並初始化的變量,定義與初始化分離:
vector<int>::iterator first;
vector<int>::iterator last;
for( first=ivec.begin(),last = ivec.end()-1;first<last;++first,--last){
cout<<*first+*last<<"/t";
++cnt;
if(cnt %6 ==0) //每行輸出六個和
cout<<endl;
}