文章标题


1. 数组 3
2. 字符串 4
3. STL 9
3.1、 参考资料 9
3.2、 容器概览 9
3.3、 通用容器的分类 9
3.4、 通用容器介绍 10
3.5、 容器使用 12
3.5.1 array 12
3.5.2 vector 14
3.5.3 list 17
3.5.4 deque 21
3.5.5 set(multiset) 24
3.5.6 map(multimap) 30
3.5.7 stack 39
3.5.8 queue(priority_queue) 41
3.5.9 unordered_set(unordered_multiset) 45
3.5.10 unordered_map(unordered_multimap) 50
4. 引用 55
4.1. 参考资料 55
4.2. 引用简介 55
4.3. 引用应用 55
4.3.1. 引用作为参数 55
4.3.2. 常引用 56
4.3.3. 引用作为返回值 56
4.3.4. 引用总结 56

1. 数组
初始化
(1)一维数组
int value[100];
int value[100] = {1,2};

指针方式:
int* value = new int[n];
delete []value; // 一定不能忘了删除数组空间

(2)二维数组
int value[9][9];
int value[9][9] = {{1,1},{2}};

指针方式1:
int (*value)[n] = new int[m][n];
delete []value; // n必须为常量,调用直观。未初始化

指针方式2:
int** value = new int* [m];
for(i) value[i] = new int[n];
for(i) delete []value[i];
delete []value; // 多次析构,存储麻烦,未初始化

指针方式3:
int * value = new int[3][4]; // 数组的存储是按行存储的
delete []value; // 一定要进行内存释放,否则会造成内存泄露

(3) 多维数组

多维数组初始化:
指针方式: int * value = new int[m][3][4]; // 只有第一维可以是变量,其他几维必须都是常量,否则会报错
delete []value; // 一定要进行内存释放,否则会造成内存泄露

  1. 字符串

include

http://www.cnblogs.com/xFreedom/archive/2011/05/16/2048037.html

http://www.cplusplus.com/reference/string/
http://www.cplusplus.com/reference/string/basic_string/

Iterators:
begin
end
rbegin
rend
Capacity:
size
length
clear
empty
Element access:
operator[]
at
back
front
Modifiers:
append
push_back
pop_back
insert
erase
replace
swap
String operations:
c_str
copy
find
rfind
find_first_of
find_last_of
substr
compare

Example:

Code:

include

include

include

using namespace std;

void printString(string s) {
for(string::iterator it = s.begin(); it != s.end(); it++) {
cout << *it;
}
cout << endl;
}

void printStringReverse(string s) {
for(string::reverse_iterator it = s.rbegin(); it != s.rend(); it++) {
cout << *it;
}
cout << endl;
}

int main(int argc, const char * argv[]) {
//
//constructor
std::string s0 (“Initial string”);

std::string s1;
std::string s2 (s0);
std::string s3 (s0, 8, 3);
std::string s4 ("A character sequence", 6);
std::string s5 ("Another character sequence");
std::string s6 (10, 'x');
std::string s7a (10, 42);
std::string s7b (s0.begin(), s0.begin()+7);

std::cout << "s1: " << s1 << "\ns2: " << s2 << "\ns3: " << s3;
std::cout << "\ns4: " << s4 << "\ns5: " << s5 << "\ns6: " << s6;
std::cout << "\ns7a: " << s7a << "\ns7b: " << s7b << '\n';


//begin, end
printString(s2);

//rbegin, rend
printStringReverse(s2);

//size, length
cout << s2.size() << endl;
cout << s2.length() << endl;

//empty
cout << s2.empty() << endl;

//clear
s2.clear();
cout << s2.empty() << endl;

//modifiers
string s = "";
//push_back, pop_back
s.push_back('a');
s.push_back('b');
s.pop_back();
cout << s <<endl;

//insert
s.insert(0, 10, 'c');
cout << s << endl;

//replace
s.replace(0, 2, "dd");
cout << s << endl;
s2="test";

//swap
s.swap(s2);
cout << s << endl;

//string operations
//c_str
s="Please split this sentence into tokens";
char * cstr = new char[s.length()+1];
strcpy(cstr, s.c_str());
cout << cstr << endl;

char * p = std::strtok (cstr," ");
while (p!=0)
{
    std::cout << p << '\n';
    p = strtok(NULL," ");
}
delete []cstr;

//copy
char buffer[20];
std::string str ("Test string...");
std::size_t length = str.copy(buffer,6,1);
buffer[length]='\0';
std::cout << "buffer contains: " << buffer << '\n';

//find
s="There are two needles in this haystack with needles.";
s2="needles";

size_t found = s.find(s2);
if(found != string::npos)
    cout << found <<endl;

found=s.find("needles are small",found+1,6);
if (found!=std::string::npos)
    std::cout << "second 'needle' found at: " << found << '\n';


//rfind
found = s.rfind("with");
if (found!=std::string::npos)
    std::cout << "rfind with: " << found << '\n';

//find_first_of
str = "PLease, replace the vowels in this sentence by asterisks.";
found = str.find_first_of("aeiou");
cout << "found: " << found <<endl;
while (found!=std::string::npos)
{
    str[found]='*';
    found=str.find_first_of("aeiou",found+1);
}
cout << str << endl;

//find_last_of
found = str.find_last_of("*");
str = str.substr(0, found);
cout << str << endl;

//substr
s = str.substr(1,2);
cout << s << endl;

//compare
string str1 = "green apple";
string str2 = "red apple";
if (str1.compare(str2) != 0)
    std::cout << str1 << " is not " << str2 << '\n';

if (str1.compare(6,5,"apple") == 0)
    std::cout << "still, " << str1 << " is an apple\n";

return 0;

}

Output:
s1:
s2: Initial string
s3: str
s4: A char
s5: Another character sequence
s6: xxxxxxxxxx
s7a: ****
s7b: Initial
Initial string
gnirts laitinI
14
14
0
1
a
cccccccccca
ddcccccccca
test
Please split this sentence into tokens
Please
split
this
sentence
into
tokens
buffer contains: est st
14
second ‘needle’ found at: 44
rfind with: 39
found: 2
PL**s*, r*pl*c* th* v*w*ls n th*s s*nt*nc by *st*r*sks.
PL**s*, r*pl*c* th* v*w*ls n th*s s*nt*nc by *st*r
L*
green apple is not red apple
still, green apple is an apple
Program ended with exit code: 0

  1. STL
    3.1﹜ 参考资料
    http://www.cplusplus.com/reference/stl/
    3.2﹜ 容器概览

顺序容器:
array, vector, list, deque
关联容器:
set, map, multiset, multimap
pair
unordered_map(hashmap)
unordered_set(hashset)
容器适配器:
stack, queue, priority_queue(heap)
3.3﹜ 通用容器的分类
(1)顺序性容器:
各元素之间有顺序关系的线性表,是一种线性关系的有序集群,顺序容器中的元素均有固定的位置,除非用删除和插入来改变它的位置,这个位置和元素本身无关,和操作时间和地点有关。
vector:从后面快速删除和插入,访问任一元素;
deque:从前面或后面快速删除和插入,访问任一元素;
list:双联表,从任何位置插入和删除;
(2)关联式容器:
非线性的树结构(二叉树结构),各元素之间没有严格的物理顺序。关联容器提供了根据元素特点排序的功能,迭代器根据元素特点“顺序”的取元素。
set:快速查找,不允许重复值;
multiset:快速查找,允许重复值;
map:一对多映射,基于关键字快速查找,不允许重复值;
multimap:一对多映射,基于关键字快速查找,允许重复值;
(3)容器适配器:
让一种已存在的容器类型采用另一种不同抽象类型的工作方式来实现的一种机制。实质上仅发生了接口转换。
stack:后进先出;
queue:先进先出;
priority_queue:最高优先级第一个出列;

3.4﹜ 通用容器介绍
(1)顺序容器
λ vector:
我们可以把它看成动态数组,创建一个vector后,它会在内存中分配一块连续的区域存储数据,初试空间可以指定也可以有vector决定(capacity()函数返回值)。当数据存储空间超过分配空间,vector会重新分配一块内存区域,这样的分配很耗时,动作如下:
首先,vector申请一块更大内存区域;
然后,将原来的数据拷贝到新的内存区域;
其次,销毁原来内存块数据;
最后,释放原来内存空间。
所以,如果vector保存的数据量很大,这样的操作会导致很糟糕的性能。只有在预知空间大小的情况下,vector的性能才是最好的。
λ List:
双向线性链表结构,指针将所有元素链接起来。根据其结构特点,List检索性能不好,需要顺序查找,检索时间与目标元素位置成正比。但是它可以对快速的删除和插入。
λ deque:
对序列两端插入和删除的容器,可以快速的随即查找。它不像vector把所有元素存储在同一内存块,而是采用多个连续的存储块,并且一个映射结构中保存对这些块和元素顺序的跟踪。deque是vector和List优缺点的结合,它是处于两者之间的一种容器。支持[]及vector.at(),性能没有vector好。
(2)关联容器
set,multiset,map,multimap都是非线性结构的树结构,采用高效的平衡检索二叉树——红黑树结构。
λ set:
一组元素的集合,元素值是唯一的,且按一定顺序排列,集合中每个元素称为集合的实例,内部采用链表结构组织;
λ multiset:
多重集合,实现方式类似set,元素值不唯一;
λ map:
提供“键–值”一一对应的数据存储能力,“键”在容器中不可重复,且按一定顺序排列;
λ multimap:
原理同上,“键”在容器中可重复。
关联容器插入和删除比vector快,比List要慢,每次插入删除后需要对元素重现排序;
关联容器检索比vector慢,但比List要快得多;
(3)容器适配器
STL提供的三种适配器可以由某一种顺序容器去实现,默认stack和queue是基于deque容器实现,prioriety_queue是基于vector实现。

3.5﹜ 容器使用
3.5.1 array
(1) reference
http://www.cplusplus.com/reference/array/array/
(2) function
Arrays are fixed-size sequence containers: they hold a specific number of elements ordered in a strict linear sequence.
(3) methods:
constructors:
array

include

include

using namespace std;

int main ()
{
//init
std::array

include

include

int main ()
{
// constructors used in the same order as described above:
std::vector first; // empty vector of ints
std::vector second (4,100); // four ints with value 100
std::vector third (second.begin(),second.end()); // iterating through second
std::vector fourth (third); // a copy of third

// the iterator constructor can also be used to construct from arrays:
int myints[] = {16,2,77,29};
std::vector fifth (myints, myints + sizeof(myints) / sizeof(int) );

std::cout << “The contents of fifth are:”;
for (std::vector::iterator it = fifth.begin(); it != fifth.end(); ++it)
std::cout << ’ ’ << *it;
std::cout << ‘\n’;

return 0;
}

include

include

using namespace std;

void printVector( vector & v) {
cout << “vector:” <

include

include

using namespace std;

void printList(list l) {
std::cout << “list: “;
for (std::list::iterator it = l.begin(); it != l.end(); it++)
std::cout << *it << ’ ‘;

std::cout << '\n';

}
int main ()
{
// constructing lists
// constructors used in the same order as described above:
std::list first; // empty list of ints
std::list second (4,100); // four ints with value 100
std::list third (second.begin(),second.end()); // iterating through second
std::list fourth (third); // a copy of third

// the iterator constructor can also be used to construct from arrays:
int myints[] = {16,2,77,29};
std::list<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );

int myints2[] = {100,20,30};
std::list<int> fifth2 (myints2, myints2 + sizeof(myints2) / sizeof(int) );

//methods
list<int> l(fifth);
printList(l);


//push
l.push_front(1);
l.push_back(2);
printList(l);

//pop
l.pop_front();
l.pop_back();
printList(l);

//insert
l.insert(l.begin(), 3, 10);
printList(l);

//erase
list<int>::iterator it1, it2;
it1 = it2 = l.begin();
advance(it2, 1);
l.erase(it1, it2);
printList(l);


//swap
list<int> l2(2,10);
l.swap(l2);
printList(l);
printList(l2);

//clear
l.clear();
printList(l);

l = l2;
printList(l);

//remove
l.remove(2);
printList(l);


//unique()
l.unique();
printList(l);



//sort
l.sort();
printList(l);

l2 = fifth2;
l2.sort();
printList(l2);

//merge
l.merge(l2);
printList(l);


//reverse
l.reverse();
printList(l);

return 0;

}
Output:
list: 16 2 77 29
list: 1 16 2 77 29 2
list: 16 2 77 29
list: 10 10 10 16 2 77 29
list: 10 10 16 2 77 29
list: 10 10
list: 10 10 16 2 77 29
list:
list: 10 10 16 2 77 29
list: 10 10 16 77 29
list: 10 16 77 29
list: 10 16 29 77
list: 20 30 100
list: 10 16 20 29 30 77 100
list: 100 77 30 29 20 16 10

3.5.4 deque
(1) reference
http://www.cplusplus.com/reference/deque/deque/
(2) function

deque (usually pronounced like “deck”) is an irregular acronym of double-ended queue. Double-ended queues are sequence containers with dynamic sizes that can be expanded or contracted on both ends (either its front or its back).

(3) Methods
constructors:
deque d
deque d(n, value)
deque d(iterator1, iterator2)
deque d(d2)
iterators:
begin
end
rbegin
rend
capacity:
size
max_size
empty
element access
front first element
back last element
operator[]
at
modifiers
push_back
pop_back
push_front
pop_front
insert insert elements
erase erase elements
swap swap two deques
clear
operations:
remove remove values
unique get list with unique elements
merge merge two sorted lists
sort sort list
reverse reverse list
(4) example:
Code:

include

include

using namespace std;

void printDeque(std::deque d) {
std::cout << “deque:”;
for (std::deque::iterator it = d.begin(); it != d.end(); ++it)
std::cout << ’ ’ << *it;

std::cout << '\n';

}
int main ()
{
// constructing deques

// constructors used in the same order as described above:
std::deque<int> first;                                // empty deque of ints
std::deque<int> second (4,100);                       // four ints with value 100
std::deque<int> third (second.begin(),second.end());  // iterating through second
std::deque<int> fourth (third);                       // a copy of third

// the iterator constructor can be used to copy arrays:
int myints[] = {16,2,77,29};
std::deque<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );

//
deque<int> d(fifth);
printDeque(d);


//push
d.push_front(1);
d.push_back(2);
printDeque(d);

//pop
d.pop_front();
d.pop_back();
printDeque(d);

//insert
d.insert(d.begin(), 3, 9);
printDeque(d);

//erase

deque<int>::iterator it1, it2;
it1 = it2 = d.begin();
advance(it2, 2);
it2++;
d.erase(it1, it2);

printDeque(d);

//swap
deque<int> d2(second);
d.swap(d2);
printDeque(d);

//clear
d.clear();
printDeque(d);


return 0;

}
Output:
deque: 16 2 77 29
deque: 1 16 2 77 29 2
deque: 16 2 77 29
deque: 9 9 9 16 2 77 29
deque: 16 2 77 29
deque: 100 100 100 100
deque:
Program ended with exit code: 0

3.5.5 set(multiset)
(1) reference
http://www.cplusplus.com/reference/set/set/
http://www.cplusplus.com/reference/set/multiset/multiset/

(2) function
Sets are containers that store unique elements following a specific order.

Multisets are containers that store elements following a specific order, and where multiple elements can have equivalent values.

(3) Methods
constructors:
set s
set s(iterator1, iterator2)
set s(s2)
iterators:
begin
end
rbegin
rend
capacity:
size
max_size
empty
modifiers
insert insert elements
erase erase elements
swap swap two deques
clear
operations:
find
count
lower_bound
upper_bound
equal_range

(4) example:
Code:
set:

include

include

using namespace std;

bool fncomp (int lhs, int rhs) {return lhs

include

include

using namespace std;

bool fncomp (int lhs, int rhs) {return lhs

include

include

using namespace std;

bool fncomp (char lhs, char rhs) {return lhs

include

include

using namespace std;

bool fncomp (char lhs, char rhs) {return lhs

include // std::cout

include // std::stack

include // std::vector

include // std::deque

using namespace std;

int main ()
{
//constructor
std::deque mydeque (3,100); // deque with 3 elements
std::vector myvector (2,200); // vector with 2 elements

std::stack<int> first;                    // empty stack
std::stack<int> second (mydeque);         // stack initialized to copy of deque

std::stack<int,std::vector<int> > third;  // empty stack using vector
std::stack<int,std::vector<int> > fourth (myvector);



std::cout << "size of first: " << first.size() << '\n';
std::cout << "size of second: " << second.size() << '\n';
std::cout << "size of third: " << third.size() << '\n';
std::cout << "size of fourth: " << fourth.size() << '\n';


//methods

//push, pop, top, empty
std::stack<int> mystack;

for (int i=1;i<=10;i++)
    mystack.push(i);

while (!mystack.empty())
{
    int n =mystack.top();
    cout << n << endl;
    mystack.pop();
}


return 0;

}
Output:
size of first: 0
size of second: 3
size of third: 0
size of fourth: 2
10
9
8
7
6
5
4
3
2
1
Program ended with exit code: 0

3.5.8 queue(priority_queue)
(1) reference
http://www.cplusplus.com/reference/queue/queue/
http://www.cplusplus.com/reference/queue/priority_queue/
(2) function
queues are a type of container adaptor, specifically designed to operate in a FIFO context (first-in first-out), where elements are inserted into one end of the container and extracted from the other.

Priority queues are a type of container adaptors, specifically designed such that its first element is always the greatest of the elements it contains, according to some strict weak ordering criterion.

template

include // std::cout

include // std::deque

include // std::list

include // std::queue

using namespace std;

int main ()
{
//constructor
std::deque mydeck (3,100); // deque with 3 elements
std::list mylist (2,200); // list with 2 elements

std::queue<int> first;                 // empty queue
std::queue<int> second (mydeck);       // queue initialized to copy of deque

std::queue<int,std::list<int> > third; // empty queue with list as underlying container
std::queue<int,std::list<int> > fourth (mylist);

std::cout << "size of first: " << first.size() << '\n';
std::cout << "size of second: " << second.size() << '\n';
std::cout << "size of third: " << third.size() << '\n';
std::cout << "size of fourth: " << fourth.size() << '\n';


//methods
int n = 0;
queue<int> q;
q.push(3);
q.push(4);

n = q.front();
cout << n << endl;

n = q.back();
cout << n << endl;

q.pop();
n = q.front();
cout << n << endl;

return 0;

}

Output:
size of first: 0
size of second: 3
size of third: 0
size of fourth: 2
3
4
4
Program ended with exit code: 0

Priority_queue:

include // std::cout

include // std::deque

include // std::list

include // std::queue

include // std::greater

using namespace std;

class mycomparison
{
bool reverse;
public:
mycomparison(const bool& revparam=false)
{
reverse=revparam;
}
bool operator() (const int& lhs, const int&rhs) const
{
if (reverse) return (lhs>rhs);
else return (lhs

include

include

include

include

using namespace std;

template
T cmerge (T a, T b) { T t(a); t.insert(b.begin(),b.end()); return t; }

void printUnorderedset(unordered_set myset) {
std::cout << “unordered_set:” ;
for ( auto it = myset.begin(); it != myset.end(); ++it )
std::cout << ” ” << *it;
std::cout << std::endl;
}
int main ()
{
//constructor
std::unordered_set first; // empty
std::unordered_set second ( {“red”,”green”,”blue”} ); // init list
std::unordered_set third ( {“orange”,”pink”,”yellow”} ); // init list
std::unordered_set fourth ( second ); // copy
std::unordered_set fifth ( cmerge(third,fourth) ); // move
std::unordered_set sixth ( fifth.begin(), fifth.end() ); // range

printUnorderedset(sixth);

//methods

//find
unordered_set<string> s(sixth);
unordered_set<string>::iterator it;
it = s.find("red");
if(it != s.end())
    cout << "found" << endl;
else
    cout << "not found << endl";

//count
int n = s.count("red");
cout << n << endl;

//insert
s.insert("red");
s.insert("color");
printUnorderedset(s);

std::array<std::string,2> myarray = {"black","white"};
s.insert(myarray.begin(), myarray.end());

printUnorderedset(s);

//erase
s.erase("color");
printUnorderedset(s);

//clear
s.clear();
printUnorderedset(s);

//swap
s.swap(sixth);
printUnorderedset(s);


return 0;

}

Output:
unordered_set: red yellow green pink blue orange
found
1
unordered_set: orange blue pink green yellow color red
unordered_set: orange blue pink green black yellow color red white
unordered_set: orange blue pink green black yellow red white
unordered_set:
unordered_set: red yellow green pink blue orange
Program ended with exit code: 0

Unordered_multiset:
// constructing unordered_sets

include

include

include

include

using namespace std;

template
T cmerge (T a, T b) { T t(a); t.insert(b.begin(),b.end()); return t; }

void printUnorderedset(unordered_multiset myset) {
std::cout << “unordered_set:” ;
for ( auto it = myset.begin(); it != myset.end(); ++it )
std::cout << ” ” << *it;
std::cout << std::endl;
}
int main ()
{
//constructor
std::unordered_set first; // empty

std::array<std::string,3> myarray1 = {"red","green","blue"};
std::array<std::string,3> myarray2 = {"orange","pink","yellow"};
std::unordered_multiset<std::string> second (myarray1.begin(), myarray1.end());    // init list
std::unordered_multiset<std::string> third (myarray2.begin(), myarray2.end()); // init list
std::unordered_multiset<std::string> fourth ( second );                    // copy
std::unordered_multiset<std::string> fifth ( cmerge(third,fourth) );       // move
std::unordered_multiset<std::string> sixth ( fifth.begin(), fifth.end() ); // range

printUnorderedset(sixth);

//methods

//find
unordered_multiset<string> s(sixth);


//insert
s.insert("red");
s.insert("color");
printUnorderedset(s);


unordered_multiset<string>::iterator it;
it = s.find("red");
if(it != s.end())
    cout << "found" << endl;
else
    cout << "not found << endl";

//count
int n = s.count("red");
cout << n << endl;

std::array<std::string,2> myarray = {"black","white"};
s.insert(myarray.begin(), myarray.end());

printUnorderedset(s);

//erase
s.erase("color");
printUnorderedset(s);

//clear
s.clear();
printUnorderedset(s);

//swap
s.swap(sixth);
printUnorderedset(s);


return 0;

}
Output:
unordered_set: red yellow blue orange pink green
unordered_set: green pink orange blue yellow color red red
found
2
unordered_set: green black pink orange blue yellow color red red white
unordered_set: green black pink orange blue yellow red red white
unordered_set:
unordered_set: red yellow blue orange pink green
Program ended with exit code: 0

3.5.10 unordered_map(unordered_multimap)
(1) reference
http://www.cplusplus.com/reference/unordered_map/unordered_map/
http://www.cplusplus.com/reference/unordered_map/unordered_multimap/
(2) function
Unordered maps are associative containers that store elements formed by the combination of a key value and amapped value, and which allows for fast retrieval of individual elements based on their keys.
template < class Key, // unordered_multimap::key_type
class T, // unordered_multimap::mapped_type
class Hash = hash, // unordered_multimap::hasher
class Pred = equal_to, // unordered_multimap::key_equal
class Alloc = allocator< pair

include

include

include

include

using namespace std;

typedef std::unordered_map

include

include

include

include

using namespace std;

typedef std::unordered_multimap

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值