问题描述:
在申明vector对象的时候不要忘了std的namespce
#include <iostream>
#include <vector>
int main()
{
int size=3;
int arr[size]={0,1,2};
std::vector<int> pell_seq(arr,arr+size);
//若使用vector<int> pell_seq(arr,arr+size);则报错
std::cout<<pell_seq.size()<<std::endl;
std::cout<<pell_seq[1]<<std::endl;
std::vector<double> vec1(3),vec2(3);
vec1[0]=0.0;
vec1[1]=1.0;
//若std::vector<double> vec1,vec2;
//vec1[0]=0.0;
//vec1[1]=1.0;
//程序崩溃!
std::cout<<vec1[0]<<vec1[1]<<std::endl;
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int value ;
vector<int> vec;
cin>>value;
vect.push_back(value)
//这样可以把value输入vect!
return 0;
}
文件的输入输出:
练习
#include<algorithm>
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
int main ()
{
ifstream in_file("file.txt");
if (!in_file)
{
cerr<<"错误";
return -1;
}
ofstream out_file("file.txt");
if (!out_file)
{
cerr<<"错误";
return -2;
}
string word;
vector<string> text;
while (in_file>>word)
{
text.push_back(word);
}
int ix;
cout<<"unsorted text:\n";
for (int i = 0; i < text.size(); i++)
{
cout<<text[i]<<' ';
}
cout<<endl;
sort(text.begin(),text.end());
out_file<<"sorted text:\n";
for (int i = 0; i < text.size(); i++)
{
out_file<<text[i]<<' ';
}
out_file<<endl;
return 0;
}
以上Essential C++的课后练习,但是出现了错误修改为如下:把ofstream放在ifstream读取的后面
#include<algorithm>
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
int main ()
{
ifstream in_file("file.txt",ios::in);
if (!in_file)
{
cerr<<"错误";
return -1;
}
string word;
vector<string> text;
while (in_file>>word)
{
text.push_back(word);
cout<<text[0]<<endl;
// cout<<"输出一个word"<<endl;
}
int ix;
cout<<"unsorted text:\n";
for (int i = 0; i < text.size(); i++)
{
cout<<text[i]<<' ';
// cout<<i<<endl;
}
cout<<endl;
cout<<"开始排序"<<endl;
sort(text.begin(),text.end());
ofstream out_file("file.txt");
if (!out_file)
{
cerr<<"错误";
return -2;
}
out_file<<"sorted text:\n";
for (int i = 0; i < text.size(); i++)
{
out_file<<text[i]<<' ';
}
out_file<<endl;
return 0;
}
字符串数组与普通数组:
练习
#include<iostream>
#include<string>
using namespace std;
const char * show(int num);
int * show1(int num);
int a=1;
int b=2;
int c=3;
int main()
{
cout<<show(1)<<endl;
cout<<show1(1)<<endl;
cout<<*show1(1)<<endl;
return 0;
}
const char * show(int num)
{
static const char* arr[]=
{
"good",
"well",
"excellent"
} ;
//这是数组指针
return arr[num];
}
int * show1(int num)
{
int *arr[3]={&a,&b,&c};
return arr[num];
}