C++基础问题 vector复制给数组
#include<iostream>#include<vector>usingnamespacestd;//编写程序把int型vector复制给int型数组。intmai...
#include <iostream>
#include <vector>
using namespace std;
// 编写程序把int 型vector 复制给int 型数组。
int main()
{
int word;
vector<int> num;
while(cin >> word){
num.push_back(word);
}
int len = num.size();
int *pt = new int[len];
size_t ix=0;
for (vector<int>::iterator iter=num.begin();iter!=num.end();++iter,++pt,++ix)
{
pt[ix] = *iter;
cout<<*pt<<" "<<*iter<<" "<<pt[ix]<<" | ";
}
delete [] pt;
return 0;
}
请问如果输入1 2 3 x
*pt的输出为何不是 1 2 3? 展开
#include <vector>
using namespace std;
// 编写程序把int 型vector 复制给int 型数组。
int main()
{
int word;
vector<int> num;
while(cin >> word){
num.push_back(word);
}
int len = num.size();
int *pt = new int[len];
size_t ix=0;
for (vector<int>::iterator iter=num.begin();iter!=num.end();++iter,++pt,++ix)
{
pt[ix] = *iter;
cout<<*pt<<" "<<*iter<<" "<<pt[ix]<<" | ";
}
delete [] pt;
return 0;
}
请问如果输入1 2 3 x
*pt的输出为何不是 1 2 3? 展开
2013-11-23
展开全部
//pt[ix]和pt++一起用导致的错误,应用另一个指针保存首地址
#include <iostream>
#include <vector>
using namespace std;// 编写程序把int 型vector 复制给int 型数组。
int main()
{
int word;
vector<int> num;
while(cin >> word){
num.push_back(word);
}int len = num.size();
int *pt = new int[len],*p=pt;
size_t ix=0;
for (vector<int>::iterator iter=num.begin();iter!=num.end();++iter,++p,++ix)
{
pt[ix] = *iter;
cout<<*p<<" "<<*iter<<" "<<pt[ix]<<" | ";
}delete [] pt;
return 0;
}
#include <iostream>
#include <vector>
using namespace std;// 编写程序把int 型vector 复制给int 型数组。
int main()
{
int word;
vector<int> num;
while(cin >> word){
num.push_back(word);
}int len = num.size();
int *pt = new int[len],*p=pt;
size_t ix=0;
for (vector<int>::iterator iter=num.begin();iter!=num.end();++iter,++p,++ix)
{
pt[ix] = *iter;
cout<<*p<<" "<<*iter<<" "<<pt[ix]<<" | ";
}delete [] pt;
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询