domenica 28 gennaio 2018

Iterate over a vector - STL C++

just to feed your curiosity

Generate a vector, and try to iterate over it in 3 different ways:

  • using iterator STL;
  • using Range C++11;
  • using indices.


the code above includes also time points, to collect some statistics

// using iterator STL
std::cout << std::endl << "using iterator STL" << std::endl;
std::chrono::steady_clock::time_point t_time1 = std::chrono::steady_clock::now();
for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it) {
        //std::cout << *it << ", ";
*it = 1;
}
std::chrono::steady_clock::time_point t_time2 = std::chrono::steady_clock::now();

//Using Range C++11
std::cout << std::endl << "Using Range C++11" << std::endl;
std::chrono::steady_clock::time_point t_time3 = std::chrono::steady_clock::now();
for (auto & value : v) {
//std::cout << value << ", ";
value = 1;
}
std::chrono::steady_clock::time_point t_time4 = std::chrono::steady_clock::now();

//Using indices
std::cout << std::endl << "Using indices" << std::endl;
std::chrono::steady_clock::time_point t_time5 = std::chrono::steady_clock::now();
for (std::vector<int>::size_type ii = 0; ii != v.size(); ii++) {
//std::cout << v[ii] << ", ";
v[ii] = 1;
}
std::chrono::steady_clock::time_point t_time6 = std::chrono::steady_clock::now();


Change freely the size of the vector, then, if you try to understand how much time is spent to perform an assignment on the i-th element... (considering a vector with more or less 1000000 values)


Chrono outcomes
 Vector Random Content integer with size 10000030
Vector iterator STL..: 5.34919  sec.us
Range c++11..........: 2.36629  sec.us
vector indices.......: 0.518377 sec.us

3 commenti: