C++におけるvector概念
2109 ワード
C++は抽象を用いて効率的なプログラミングを行う方法を提供する.標準ライブラリは良い例です.
標準ライブラリは、多くのコンテナクラスと一連の汎用アルゴリズムを定義し、プログラマがより簡潔で抽象的で効率的にプログラムを記述できるようにします.
コンテナは特定のタイプのオブジェクトの集合を収容し、
シーケンスコンテナ:
単一のタイプの要素を集約してコンテナになり、場所に応じてこれらの要素を格納およびアクセスします.これがシーケンスコンテナです.シーケンスコンテナの要素の配列順序は要素値に関係なく、要素がコンテナに追加される順序によって決まります.
標準ライブラリには、次の3つの順序付きコンテナタイプが定義されています.
vector;
list;
deque
標準ライブラリには、次の3つのコンテナアダプタも用意されています.
stack;
queue;
priority_queue.
vectorの例1:
vector例2:
標準ライブラリは、多くのコンテナクラスと一連の汎用アルゴリズムを定義し、プログラマがより簡潔で抽象的で効率的にプログラムを記述できるようにします.
コンテナは特定のタイプのオブジェクトの集合を収容し、
シーケンスコンテナ:
単一のタイプの要素を集約してコンテナになり、場所に応じてこれらの要素を格納およびアクセスします.これがシーケンスコンテナです.シーケンスコンテナの要素の配列順序は要素値に関係なく、要素がコンテナに追加される順序によって決まります.
標準ライブラリには、次の3つの順序付きコンテナタイプが定義されています.
vector;
list;
deque
標準ライブラリには、次の3つのコンテナアダプタも用意されています.
stack;
queue;
priority_queue.
vectorの例1:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec;
vector<int> vec1(10, -1);
vector<int> vecMyHouse(10); //define a known length vector.
vec = vec1;
int i;
cout << "Please input a integer:";
cin >> i;
vecMyHouse.resize(i);
for(i = 0; i < vecMyHouse.size(); i++)
{
vecMyHouse[i] = i;
}
for(i = 0; i < vecMyHouse.size(); i++)
{
cout << vecMyHouse[i] << endl;
}
// vec.clear();
vec.push_back(100);
for(i = 0; i < vec.size(); i++)
{
cout << vec[i] << endl;
}
cout << vecMyHouse.size() << endl;
system("pause");
return 0;
}
vector例2:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
int num;
string word;
vector<string> text;
cout << "Please input the number of element that we want to insert:";
cin >> num;
cout << "Please input the element that we should insert:" << endl;
while((cin >> word) && (--num))
{
text.push_back(word);
}
cout <<"First Method:
";
cout << "Words read are:
";
for(int i = 0; i < text.size(); i++)
{
cout << text[i] << endl;
}
cout << "Second Method" << endl;
cout << "Words read are:
";
for(vector<string>::iterator it = text.begin(); it != text.end(); ++it)
{
cout << *it << endl;
}
system("pause");
return 0;
}