stl幾個(set map vector string)用法

來源:互聯網
上載者:User

string使用總結

1.初始化

string s0;
string s1("hello");
string s2(5, 'a');         //s2 = aaaaa;
string s3(s1);                 // s3 = hello
char str[100] = "aaaaabbbbbaaaaaaaaaaaaaaaaa";
string s4(str, 5);              //s4 = aaaaa;
string s5(str+5, str+10);       //s5 = bbbbb;

2.find函數

string s("bbabbabba"),s1("a");
s.find('a', pos = 0);
s.find(s1, pos = 0);
s.find("ab", pos = 0, num);
總結:
(1)find()返回一個size_type類型的資料,可以這樣去判讀是否找到:
basic_string<char>::size_type t = s.find(...);
if(t == string::npos) cout << "not find" << endl;
npos是string的一個靜態成員變數,所以用string類名來修飾。
(2)第二個參數表示尋找的起始位置,預設為0;
(3)如果是尋找c類型的字串還可以有第三個參數,表示要找這個字串的前幾個字元。
如(“absdfasdf”,5,2)表示,在原字串的下表為5的位置開始找“ab”;
(4)具有相同文法的還有下面幾個函數:
find_first_of(): 找第一次滿足條件的位置
find_last_of(): 找最後一個滿足條件的位置
find_first_not_of(): 找第一個不合格位置
find_last_not_of():找最後一個不合格位置
rfind(): 從後往前找

3.size_type capacity( ) const;
返回已經分配的儲存空間大小。

4.length()和size()返回同樣的值,都是string的大小。
length()是以前的string實現的函數。
size()是為了同STL融合,加入的函數。

5.substr(start = 0, num = npos);
返回string的一部分,有開始位置和個數,兩個參數。

6.resize(num = 0, char = 0);
/*
string s("abcd");
s.resize(s.size()+2, '!'); //s = "abcd!!"
s.resize(s.size()+20); // s= "abcd",添加在後面的都是'/0'
s.resize(s.size()-2); // s = ab;
*/

7.assign()函數

s.assign(cstr, num = 0);            //c_char*類型的從0開始拷貝num個進去。
s.assign(s2);                 //string類型的s2
s.assign(s2, start, num);                // string類型的s2,從第start個位置開始,拷貝num個
s.assign(num, char);                    / / 拷貝num個char進去
s.assign(s2.begin(), s2.end() );             //迭代器版本

8.append()函數
同上!

10.swap(s2);

11.push_back(ch);

12.insert()函數

s1.insert(pos, *ptr);
s1.insert(pos, *ptr, num);
s1.insert(pos, s2);
s1.insert(pos, s2, start, num);
s1.insert(pos, num, ch);              //在pos初加入num個char
s1.insert(iterator, s2.begin(), s2.end());
s1.insert(iterator, num, ch);

13.erase()函數

erase(s.begin(), s.end());
erase(iterator);
erase(pos = 0, num = npos);       //預設全部刪除

14.replace()函數

replace(pos, num, *ptr, num2 = npos); //用*ptr的num2個元素替換原string從pos開始的num個元素
replace(pos, num, s2, num2 = npos);
replace(pos, num, num2, ch); //原stringpos位置處的num個由num2個ch替換
replace(iter_first, iter_last, *ptr);
replace(iter_first, iter_last, s2);
replace(iter_first, iter_last, num2, ch);
replace(iter_first, iter_last, iter2_first, iter2_last,);

set的使用

#include <iostream>
#include <set>
#include <vector>
using namespace std;

int main()
{
vector<int> v;
for(int i = 0; i < 5; ++i)
   v.push_back(i);

set<int> sett(v.begin(), v.end());    //可以用其他容器初始化set
set<int>::iterator iter, iter2;

sett.insert(8);   //插入元素

iter = sett.find(2);         //查看元素是否存在的方法一:find()
if(iter != sett.end())
   cout << "ok, found it" << endl;

for(iter = sett.begin(); iter != sett.end(); ++iter)
   cout << *iter << endl;

sett.erase(1);   //刪除元素

if(!sett.count(1))   //查看元素是否存在的方法二:count()
   cout << "ok, Not found it" << endl;

iter2 = sett.upper_bound(4);
for(iter = sett.begin(); iter != iter2; ++iter)
   cout << *iter << endl;

return 0;
}

注意事項:

1.當只想知道一個值是否存在時,使用set容器是最合適的。
2.正如不能修改map中元素的鍵部分一樣,set中的鍵也為const。在擷取指向set中某元素的迭代器後,只能對其做讀操作,而不能做寫操作

lower_bound()
Returns an iterator to the first element in a set with a key that is equal to or greater than a specified key.

upper_bound()
Returns an iterator to the first element in a set with a key that is greater than a specified key.
 
map的使用

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main()
{
map<string, int> m;
map<string, int>::iterator iter;
typedef map<string, int>::value_type mType;

string s;
while(cin >> s)  
   m[s]++;         //很重要的一種插入元素的方法,下標法

m.insert( make_pair("hello", 1) );    //另外兩種插入元素的辦法
m.insert( mType("world", 2) );

for(iter = m.begin(); iter != m.end(); ++iter)
   cout << iter->first << " " << iter->second << endl;    //讀取元素的辦法

iter = m.find("hello");           //尋找元素的方法(1)find函數,注意檢測的辦法
if(iter != m.end())
   cout << "yes, found it" << endl;

m.erase(iter);            //刪除元素的erase函數,還有第三個版本,參數是iterator的begin和end
m.erase("world");

if(m.count("world"))        //尋找元素的方法(2)cout函數,返回0或者1,表示有或無
   cout << "error" << endl;

return 0;
}

注意事項:

使用下標訪問map與使用下標訪問數組或vector的行為截然不同:用下標訪問不存在的元素將導致在map容器中添加一個新的元素,它的鍵即為該下標值。

multimap的使用

#include <iostream>
#include <map>
using namespace std;

int main()
{
typedef multimap<int, int> M;
M m;
multimap<int, int>::iterator iter;
typedef pair<int, int> Int_pair;

m.insert(Int_pair(3,3)); //插入一個元素的辦法,不同於map
m.insert(Int_pair(4,4));
m.insert(Int_pair(3,4));
m.insert(Int_pair(2,2));

for(iter = m.begin(); iter != m.end(); iter++)     //遍曆multimap的方法,跟其他的容器一樣
   cout << iter->first << " " << iter->second << endl;

iter = m.find(2);    //find返回的是第一個找到的元素的位置
if(iter == m.end()) cout << "can not find 2/n";   //注意判斷沒有找到的辦法
else cout << iter->second << endl;

pair<M::iterator, M::iterator> range;    //前面說了find只能返回第一個位置
range = m.equal_range(3);                    //要是想得到全部,只能這樣啦。。。
for(iter = range.first; iter != range.second; iter++)
   cout << iter->first << " " << iter->second << endl;

int num = m.count(3);         //恩,返回滿足條件的元素的個數,因為是multimap嘛。。。
cout << num << endl;
return 0;
}

還有幾個函數也挺有用的,列在這裡吧:

clear() :清空

empty(): 測試是否為空白

erase(): 刪除某個元素,或是某個區間內的元素

low_bound(); 比輸入的元素小的第一個元素的iterator

upper_bound(): 比輸入的元素大的第一個元素的iterator

也支援rbegin()和rend()函數

vector實現多維陣列

#include <iostream>
#include <vector>
using namespace std;

vector< vector<int> >m (3, vector<int>(5));

int main()
{
for(int i = 0; i < m.size(); i++)
{
   for(int j = 0; j < m[i].size(); j++)
    cout << m[i][j] << "/t";
   cout << endl;
}
return 0;
}

vector的建構函式中,有下面的形式:
vector(
   size_type _Count,
   const Type& _Val
);

採用這種形式,可以實現,每維數組大小不同。可以重新確定每維數組的大小:

void reshape_m(int ns)
{
for(int i = 0; i < m.size(); i++)
   m[i].resize(ns);
}

所有的sort演算法的參數都需要輸入一 個範圍,[begin, end)。這裡使用的迭代器(iterator)都需是隨機迭代器(RadomAccessIterator)

以下是所有STL sort演算法函數的名字列表:

函數名
 功能描述
 
sort
 對給定區間所有元素進行排序
 
stable_sort
 對給定區間所有元素進行穩定排序
 
partial_sort
 對給定區間所有元素部分排序
 
partial_sort_copy
 對給定區間複製並排序
 
nth_element
 找出給定區間的某個位置對應的元素
 
is_sorted
 判斷一個區間是否已經排好序
 
partition
 使得符合某個條件的元素放在前面
 

注意最後一個,合格是放在前半部分的。可以用splice提取想要的部分。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.