STL way to access more elements at the same time in a loop over a container

The most STLish way I can imagine: std::partial_sum(std::begin(v), std::end(v), std::begin(v), std::multiplies<double>()); Example: #include <iostream> #include <vector> #include <iterator> #include <numeric> #include <functional> int main() { std::vector<double> v{ 1.0, 2.0, 3.0, 4.0 }; std::partial_sum(std::begin(v), std::end(v), std::begin(v), std::multiplies<double>()); std::copy(std::begin(v), std::end(v), std::ostream_iterator<double>(std::cout, ” “)); } Output: 1 2 6 24 Live demo link.

Python for loop question

Python’s for loops are different. i gets reassigned to the next value every time through the loop. The following will do what you want, because it is taking the literal version of what C++ is doing: i = 0 while i < some_value: if cond…: i+=1 …code… i+=1 Here’s why: in C++, the following code … Read more

passing index from for loop to ajax callback function (JavaScript)

You could use a javascript closure: for (var i = 0; i < arr.length; i++) { (function(i) { // do your stuff here })(i); } Or you could just use $.each: var arr = [2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010]; $.each(arr, function(index, value) { $.ajaxSetup({ cache:false }); $.getJSON(“NatGeo.jsp”, { ZipCode: value, … Read more

How to start and stop/pause setInterval?

See Working Demo on jsFiddle: http://jsfiddle.net/qHL8Z/3/ $(function() { var timer = null, interval = 1000, value = 0; $(“#start”).click(function() { if (timer !== null) return; timer = setInterval(function() { $(“#input”).val(++value); }, interval); }); $(“#stop”).click(function() { clearInterval(timer); timer = null }); }); <script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script> <input type=”number” id=”input” /> <input id=”stop” type=”button” value=”stop” /> <input id=”start” type=”button” … Read more