#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void test_init() {
cout << "test_init: " << endl;
vector <double> content(20);
cout << content.size() << endl;
vector <int> v(10, 90);
cout << v.size() << endl;
vector <int>::iterator it = v.begin();
while(it != v.end()) {
cout << *it << ' ';
++it;
}
cout << endl;
}
void test_push_back() {
cout << "test_push_back :" << endl;
vector<int> v;
for(int i = 0; i < 10; i++) {
v.push_back(i);
}
vector <int>::iterator it ;
it = v.begin();
while(it != v.end()) {
cout << *it << ' ';
++it;
}
cout << endl;
cout << "v.size = " << v.size() << endl;
}
void test_array() {
vector <int> v(100);
for(int i = 0; i < 20; i++) {
v[i] = 2*i + 1;
}
for(int i = 0; i < 20; i++) {
cout << v[i] << " ";
}
cout << endl;
}
void test_insert() {
std::vector<int> myints;
cout <<"0.size: " << myints.size() << endl;
for (int i=0; i<10; i++) {
myints.push_back(i);
}
cout << "1. size: " << myints.size() << '\n';
myints.insert (myints.end(),10,100);
vector <int>::iterator it ;
for(it = myints.begin(); it != myints.end(); ++it) {
cout << *it << " ";
++it;
}
cout << endl;
cout << "2. size: " << myints.size() << '\n';
myints.pop_back();
std::cout << "3. size: " << myints.size() << '\n';
}
void test_find() {
vector <int> v;
v.push_back(50);
v.push_back(67);
v.push_back(99);
v.push_back(2991);
v.push_back(23);
v.push_back(44);
v.push_back(23);
v.push_back(32);
v.push_back(9999);
cout << "The contents of the vector are: " << endl;
vector <int>::iterator it = v.begin();
while(it != v.end()) {
cout << *it << " ";
++it;
}
cout << endl;
///find an element in the array using the 'find' algorithm...
vector <int>::iterator point = find(v.begin(), v.end(), 2991 );
///check if value was found
if(point != v.end()) {
int position = distance(v.begin(), point);
cout << "value " << *point;
cout << "found in the vector at position:" << position<< endl;
}
}
int main ()
{
test_init();
test_push_back();
test_array();
test_insert();
test_find();
return 0;
}
///强烈推荐网址:http://www.cplusplus.com/reference/vector/vector/insert/
STL_vector常见用法举例
最新推荐文章于 2024-07-15 15:38:19 发布