cpp std - ghdrako/doc_snipets GitHub Wiki

Using std::vector

std::vector is defined in the header.

If we know the approximate number of elements that we will need in the vector, we can optimize its use by initially allocating that capacity for the vector using the reserve() method. For example, the following code reserves a capacity for 10,000 elements(to avoiding resizing during element insertion):

std::vector<int> vec;
vec.reserve(10000);

To reduces the capacity so that it fits the size of the vector.

vec.shrink_to_fit();

Using std::list

The list has the push_front() function, which inserts an element at the front of the list. This is done efficiently because std::list represents a doubly linked list.

std::list<double> lst;
lst.push_back(4.2);
lst.push_front(3.14);
// the list contains: "3.14 -> 4.2

Iterating containers

std::vector<int> vec{1, 2, 3, 4, 5};
for (int ix = 0; ix < vec.size(); ++ix) {
  std::cout << vec[ix] << ", ";
}
std::vector<double> a{1, 2, 3, 4, 5};
std::vector<double>::const_iterator i;
for(i=a.begin(); i!=a.end(); ++i){
        std::cout<<(*i)<<std::endl;
}

We are using a const iterator because we do not intend to modify the contents of the vector. The member function begin() returns an iterator that “points” to the first element in the sequence.The member function end() returns an iterator that “points” to one-past-the-last-element in the sequence.

we cannot use the preceding loop to iterate list elements. However, we can loop over a list (and vector) with a range-based for loop, as follows:

std::list<double> lst{1.1, 2.2, 3.3, 4.2};
for (auto& elem : lst) {
  std::cout << elem << ", ";
}
  • capacity() - currently allocated storage of a vector
  • size() - how many elements are currently contained by the vector
#include <vector>
#include <iostream>
//...
std::vector<int> array;
int i = 999;          // some integer value
array.reserve(10);    // make room for 10 elements
array.push_back(i);
std::cout<<array.capacity()<<std::endl;
std::cout<<array.size()<<std::endl;

return

9
1
⚠️ **GitHub.com Fallback** ⚠️