C++ STL 中 vector 的一些用法

#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int>str;
vector<int>::iterator a, b;
int i;
str.clear();
str.push_back(‘a’);
cout << “str.empty() = ” << str.empty() << endl << endl;
str.pop_back();
cout << “str.empty() = ” << str.empty() << endl << endl;

for( i = 0; i < 10; i++ )str.push_back(i+’A');
cout << “str.size() = ” << str.size() << endl;
for( i = 0; i < str.size(); i++ )cout << (char)str.at(i) << ” “;
cout << endl << endl;
a = str.begin();
b = str.end();
vector<int>an_str(a, b);
for( i = 0; i < an_str.size(); i++ )cout << (char) an_str[i] << ” “;
cout << endl << endl;

vector<int>ostr(5, 66);
for( i = 0; i < ostr.size(); i++ )cout << (char) ostr.at(i) << ” “;
cout << endl << endl;

cout << “str == an_str: ” << (str == an_str) << endl;

cout << “str != an_str: ” << (str != an_str) << endl;

cout << “str > ostr: ” << (str > ostr) << endl;

cout << “str < ostr: ” << (str < ostr) << endl;

cout << endl << endl;

cout << “str.back() = ” << (char)str.back() << endl << “an_str.front() = ” << (char)an_str.front() << endl << “ostr.back() = ” << (char)ostr.front() << endl;
cout << endl << endl;

int s[10];
for( i = 0; i < 10; i++ )s[i] = ‘a’+i;
vector< int > vs( s,s+10 );
for(i = 0; i < vs.size(); i++ )cout << (char)vs.at(i) << ” “;
cout << endl << endl;

vs.assign(10,’A');
for( i = 0; i < vs.size(); i++ )cout << (char)vs[i] << ” “;
cout << endl << endl;

vs.assign(s,s+5);

for( i = 0; i < vs.size(); i++ )cout << (char)vs[i] << ” “;
cout << endl << endl;

vector<int>::iterator p, q;
int vs_size = vs.size();

for( i = 0; i < vs_size; i++ )
{
p = vs.begin();
for( q = vs.begin(); q < vs.end(); q++ )
{
cout << (char)(*q);
}
cout << endl;

vs.erase(p);

}

cout << “vs.empty() = ” << vs.empty() << endl << endl;

vs.insert(vs.begin(),’a');
cout << (char)vs[0]<< endl;
cout << “vs.empty() = ” << vs.empty() << endl << endl;
vs.clear();
for( i = 0; i < 10; i++ )vs.insert(vs.begin(),i+’a');
for( i = 0; i < vs.size(); i++ )cout << (char)vs[i] << ” “;
cout << endl << endl;

p = vs.begin();
for( i = 0; i < 5; i++ )p++;

//vs.insert(p,5,’A');
vs.insert(p,str.begin(),str.end());
for( i = 0; i < vs.size(); i++ )cout << (char)vs[i] << ” “;
cout << endl << endl;

cout << vs.max_size() << endl;

}

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>