前面提到的emplace_back就是C++11所增加的内容。
所以这篇博客就是想罗列一下C++11对vector容器的扩充。
std::vector::cbegin和std::vector::cend
这两个方法是与std::vector::begin和std::vector::end相对应的,从字面就能看出来,多了一个’c’,顾名思义就是const的意思。
所以:
std::vector::cbegin: Returns a const_iterator pointing to the first element in the container.
std::vector::cend: Returns a const_iterator pointing to the past-the-end element in the container.
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector = {10,20,30,40,50};
std::cout << "myvector contains:";
for (auto it = myvector.cbegin(); it != myvector.cend(); ++it)
std::cout << ‘ ‘ << *it;
std::cout << ‘\n‘;
return 0;
}
Output:
myvector contains: 10 20 30 40 50
std::vector::crbegin和std::vector::crend
这两个方法就不解释了,与上面的相比就是多了个’r’, reverse的缩写,反转迭代器,代码就省略了。
std::vector::emplace
之前已经对emplace_back进行了讨论,其实还有一个方法叫emplace。
我想说的就是,emplace之于emplace_back就像insert之于push_back。
看英文描述就直观:
emplace:Construct and insert element
emplace_back:Construct and insert element at the end
如何使用:
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector = {10,20,30};
auto it = myvector.emplace ( myvector.begin()+1, 100 );
myvector.emplace ( it, 200 );
myvector.emplace ( myvector.end(), 300 );
std::cout << "myvector contains:";
for (auto& x: myvector)
std::cout << ‘ ‘ << x;
std::cout << ‘\n‘;
return 0;
}
Output:
myvector contains: 10 200 100 20 30 300
std::vector::data
Returns a direct pointer to the memory array used internally by the vector to store its owned elements.
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector (5);
int* p = myvector.data();
*p = 10;
++p;
*p = 20;
p[2] = 100;
std::cout << "myvector contains:";
for (unsigned i=0; i<myvector.size(); ++i)
std::cout << ‘ ‘ << myvector[i];
std::cout << ‘\n‘;
return 0;
}
Output:
myvector contains: 10 20 0 100 0
std::vector::shrink_to_fit
Requests the container to reduce its capacity to fit its size.
就是减少空间
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector (100);
std::cout << "1. capacity of myvector: " << myvector.capacity() << ‘\n‘;
std::cout << "1. size of myvector: " << myvector.size() << ‘\n‘;
myvector.resize(10);
std::cout << "2. capacity of myvector: " << myvector.capacity() << ‘\n‘;
std::cout << "2. size of myvector: " << myvector.size() << ‘\n‘;
myvector.shrink_to_fit();
std::cout << "3. capacity of myvector: " << myvector.capacity() << ‘\n‘;
std::cout << "3. size of myvector: " << myvector.size() << ‘\n‘;
return 0;
}
//输出
1. capacity of myvector: 100
1. size of myvector: 100
2. capacity of myvector: 100
2. size of myvector: 10
3. capacity of myvector: 10
3. size of myvector: 10
此时,就是要明白size和capacity的区别,也就会更加理解resize和reserve的区别了!