您的位置:首页 > 编程语言 > C语言/C++

c++之STL(3) Vector容器

2016-07-21 09:22 537 查看
vector是一个动态数组,是一个类模板(class template)

vector对象的定义和初始化

vcotor对象的操作

vector<T>::size_type

vector下标操作不添加元素

//

#include<iostream>
#include<string>
//
#include<vector>

using std::vector;
using std::string;
using std::cout;
using std::endl;

int main()
{
//using namespace std;
//
vector<int> ivec;
vector<double> dvec;
vector<string> svec;

vector<int> a;
vector<int> b(10, 2);	// 存储10 个2
a.push_back(1);
a.push_back(2);
a.push_back(3);

b.push_back(10);
b.push_back(11);
cout << a.size() << endl;
cout << b.size() << endl;

//vector容器的循环
for (vector<int>::size_type i = 0; i != a.size(); i++)
{
cout << a[i] << endl;
}
for (vector<int>::size_type i = 0; i != b.size(); i++)
{
cout <<b[i] << endl;
}

//
system("pause");
return 0;
}
对于容器的循环尽量要用 size_type类型

#include<iostream>
#include<string>
//
#include<vector>

using namespace std;

int main()
{
//
vector<int> vec1;
vec1.push_back(10);
vec1.push_back(11);
vec1.push_back(12);

vector<int> vec2(vec1);	//vec1复制到vec2
vector<int> vec4(10, -1);
vector<int> vec6(10);	// 10个0

vector<string> v5(10, "hello!");
vector<string> v7(10);	// 10个空串

cout << vec1[0] << endl;
cout << vec2[0] << endl;
cout << vec4[0] << endl;
cout << vec6[0] << endl;
cout << v5[0] << endl;
cout << v7[0] << endl;

vec1[0] = 100;
cout << vec1[0] << endl;
v7[0] = "World!";
cout << v7[0] << endl;

//
system("pause");
return 0;
}


#include<iostream>
#include<string>
//
#include<vector>

using namespace std;

int main()
{
//
vector<int> vec1;
cout << vec1.size() << endl;

int k;

for (vector<int>::size_type ix = 0; ix != 5; ++ix)
{
cin >> k;
vec1.push_back(k);
}

cout << "显示vector里面的数据:" << endl;
for (vector<int>::size_type m = 0; m != vec1.size(); m++)
{
cout << vec1[m] << endl;
}

//
cout << "请输入一些字符串!" << endl;
string word;
vector<string> text;
while (cin >> word)
text.push_back(word);

cout << "你输入的字符串是:" << endl;
for (vector<string>::size_type i = 0; i != text.size(); i++)
{
cout << text[i] << endl;
}
//
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: