Is There a Standard Algorithm to Iterate Over a Range? - c++

I need to call a lambda with every int in a range. Is there a standard algorithm that does this?
Ideally something equivalent:
for(auto i = 13; i < 42; ++i)[](int i){/*do something*/}(i);

There's nothing built-in, no.
You can do it yourself with a hand-crafted iterator and std::for_each, or use Boost's counting iterators to help you along:
#include <boost/iterator/counting_iterator.hpp>
#include <algorithm>
#include <iostream>
int main()
{
std::for_each(
boost::counting_iterator<int>(13),
boost::counting_iterator<int>(42),
[](int i){ std::cout << i << ' '; }
);
}
Output:
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
(live demo)

I don't know of anything in the standard library that can produce a range of numbers on demand like you're asking for. But this can be done a couple of different ways using Boost.
Use Boost.Range to generate an integer range and use it with the range version of for_each
boost::for_each(boost::irange(13, 42), [](int i){ std::cout << i << ' '; });
Use boost::counting_iterator from Boost.Iterator and pass those to std::for_each
std::for_each(boost::make_counting_iterator(13),
boost::make_counting_iterator(42),
[](int i){ std::cout << i << ' '; });
Live demo

As the other answers have mentioned if Boost is an option there is a better way to do this. If not, the best way is in the original question:
for(auto i = 13; i < 42; ++i)[](int i){/*do something*/}(i);
However, the future is bright, chris has mentioned proposal N4128 which is suggesting incorporating ranges into the standard alongside iterators.
Now the draft is still in an early state, so there's a lot of clarification that is needed before how this will be used is nailed down. But one of the concepts is that all the STL algorithms would be overloaded to take views which is a thin wrapper providing access to the contained elements, but also an intelligent end position.
Although a more complex example, chosen to showcase the power of view, the author's example in Motivation and Scope uses iota, which is exactly what we want:
int total = accumulate(view::iota(1) |
view::transform([](int x){return x*x;}) |
view::take(10), 0);
For our purposes we'd need to use generate_n in a for_each algorithm:
for_each(view::generate_n(28,[]{static int i = 13; return i++;}),[](int i){/*do something*/});
This would cause generate_n to be called 28 times (13 + 28 = 41), the created view would provide iteration over these numbers, feeding them into our original lambda in the for_each.
chris has suggested that instead of generate_n a modification of iota might do the trick: iota(13, 41) It is key to note that whatever is used must have an end condition, because view lazily calls the generator, until no more items are requested. So this for_each(view::iota(10), [](int i){/*do something*/}); defines an infinite loop.

Related

How to iterate two vectors in one for loop?

I'm only showing my functions because I believe the problem is in my for loop.
DataStoreVectors::DataStoreVectors() {
}
void DataStoreVectors::addItem(string item1, int item2) {
videoGame.push_back(item1);
gameSize.push_back(item2);
}
void DataStoreVectors::listItems()
{
vector <string>::iterator pv;
vector <int>::iterator px;
for (pv = videoGame.begin(); pv < videoGame.end(); pv++)
{
for (px = gameSize.begin(); px < gameSize.end(); px++)
cout << *pv << " " << *px << endl;
}
}
When I try to print out the data in my two arrays, it prints out the name of each video game about 6 times and assigns my int values to them like so:
Valorant 8
Valorant 70
Valorant 50
Valorant 1
Valorant 26
Valorant 35
Fortnite 8
Fortnite 70
Fortnite 50
Fortnite 1
Fortnite 26
Fortnite 35
Doom Eternal 8
Doom Eternal 70
Doom Eternal 50
Doom Eternal 1
Doom Eternal 26
Doom Eternal 35
Minecraft 8
Minecraft 70
Minecraft 50
Minecraft 1
Minecraft 26
Minecraft 35
Apex Legends 8
Apex Legends 70
Apex Legends 50
Apex Legends 1
Apex Legends 26
Apex Legends 35
Control 8
Control 70
Control 50
Control 1
Control 26
Control 35
Is this possible? Would it be better to make a struct? I'm trying to figure out the right way to print out two vectors side by side.
It's quite simple to keep the iterators synchronized in position. Just add another increment in the for loop like this:
vector <int>::iterator px = gameSize.begin(); // << Add this
for (pv = videoGame.begin(); pv < videoGame.end(); pv++, px++)
// ^^^^^^ Add this
Ensure that both vectors have the same size, or the vector px points to is at least bigger than the other one (videoGame) though.
You could use a range-v3 zip view.
for (auto [game, size] : ranges::views::zip(videoGame, gameSize))
{
std::cout << game << " " << size << std::endl;
}
If the data is linked then you should make a struct from this.
I also recommend giving your parameters a more descriptive name in addItem such as addItem(string gameName, int gameSize) and maybe rename the vectors to use the plural form such as videoGames and gameSizes.
Regarding the iteration over two vectors you can iterate over those with a simple int index (this assumes both vectors have the same size as it seems to be in your case):
for (int i = 0; i < videoGame.size(); ++i)
{
cout << videoGame[i] << " " << gameSize[i] << endl;
}
You can increment each iterator in the same loop, but both arrays would need to be the same size, however it's a horrible bug prone approach, your single array of a struct that includes both fields is a far better approach.

Knapsack problem with multiple availabe packages using dynamic programming

Hello and thanks for helping!
So we've got a list of fireworks containing 1) Number in stock 2) Number of fireworks in this package 3) Diameter which equals the noise and
4) The price.
This is the list:
25 17 10 21
10 15 10 18
5 16 10 19
10 15 12 20
15 9 11 12
10 7 28 23
8 7 16 11
10 6 16 10
25 10 18 25
25 12 18 27
10 5 40 35
60 40 5 27
5 25 30 90
50 1 60 8
Our task is to create a shopping list and buy fireworks so we get the highest possible noise. We've got a knapsack capacity of 1000€. We're also supposed to solve this without using tables (so with dynamic programming instead).
I only use one class called Package which contains the four constraints as shown above.
At first I thought it would make sense to try to write an algorithm for a normal knapsack, so just with the price and the diameter (=weight). I tested it with a different list and it worked perfectly fine. I just iterated through all packages and then again used a nested for loop to find the best constellation (exhaustive search). My next idea was to merge the number of fireworks per package with the diameter, because fireworks can only be bought in a full package.
The only thing left which I still haven't found out is what to do with the amount of packages in stock. Like, with my current algorithm it just buys all packages of a firework until the knapsack is full. But obviously that won't be correct.
void knapsack(vector<Package*> stock){
vector<int> indices, tmp_indices;
int noise,tmp_noise= 0;
int price;
for (unsigned int i = 0; i < stock.size(); i++) {
price = stock[i]->price;
noise = stock[i]->diameter*stock[i]->number_fireworks;
indices.push_back(i);
for (unsigned int j = 0; j < stock.size(); j++) {
if (i != j) {
if (price+stock[j]->price<= BUDGET) {
price+=stock[j]->price;
noise+=stock[j]->diameter*stock[j]->number_fireworks;
indices.push_back(j);
}
}
}
// After second loop we have a new possible constellation
// Check if the previous constellation had a lower value and if so, set it to the current one
if (noise > tmp_noise) {
tmp_noise = noise;
tmp_indices.clear();
// tmp save
for (auto &index : indices) {
tmp_indices.push_back(index);
}
}
price= 0;
noise = 0;
indices.clear();
}
// Best constellation found, Print the shopping list
cout << "\Stock.\tNum\Diameter.\Price\n" << endl;
for(unsigned int i = 0; i < tmp_indices.size(); i++) {
cout << stock[tmp_indices[i]]->stock<< "\t";
cout << stock[tmp_indices[i]]->number_fireworks<< "\t";
cout << stock[tmp_indices[i]]->diameter<< "\t";
cout << stock[tmp_indices[i]]->price<< "\t\n";
}
}
We've been told that we should be able to spend exactly 1000€ to get the correct constellation of fireworks. My idea was to add another for loop to iterate through the amount of available packages, but that didn't really work...
This was our first lesson and I'm a bit desperate, because we have only learned how to solve a knapsack problem with 2 constraints and by using a table R.
Edit: Since one user insisted to get a specific question, here it is: Is the idea of using another loop to include the third constraint correct or is there a better/easier way of doing it? Or is it possible that I need a completely different approach for a knapsack with 3 instead of 2 constraints?
Thanks for help in advance

c++ string capacity change during copy assignment

In the C++ Standard std:string follows an exponential growth policy, therefore I suppose the capacity() of string during concatenation will always be increased when necessary. However, when I test test.cpp, I found that in the for-loop, only every two times will the capacity() be shrunk back to length() during assignment.
Why isn't this behavior depending on the length of string, but depending on how frequent I change the string? Is it some kind of optimization?
The following codes are tested with g++ -std=c++11.
test.cpp:
#include <iostream>
int main(int argc, char **argv) {
std::string s = "";
for (int i = 1; i <= 1000; i++) {
//s += "*";
s = s + "*";
std::cout << s.length() << " " << s.capacity() << std::endl;
}
return 0;
}
And the output will be like this:
1 1
2 2
3 4
4 4
5 8
6 6 // why is capacity shrunk?
7 12
8 8 // and again?
9 16
10 10 // and again?
11 20
12 12 // and again?
13 24
14 14 // and again?
15 28
16 16 // and again?
17 32
...
996 996
997 1992
998 998 // and again?
999 1996
1000 1000 // and again?
When you do this:
s = s + "*";
You're doing two separate things: making a new temporary string, consisting of "*" concatenated onto the end of the contents s, and then copy-assigning that new string to s.
It's not the + that's shrinking, it's the =. When copy-assigning from one string to another, there's no reason to copy the capacity, just the actual used bytes.
Your commented-out code does this:
s += "*";
… is only doing one thing, appending "*" onto the end of s. So, there's nowhere for the "optimization" to happen (if it happened, it would be a pessimization, defeating the entire purpose of the exponential growth).
It's actually not convered by the C++ standard what happens to capacity() when strings are moved, assigned, etc. This could be a defect. The only constraints are those derivable from the time complexity specified for the operation.
See here for similar discussion about vectors.

tactics to think as a computer

I have some question from the exam in which I need to deduce the output of the following code:
01 int foo(int a) {
02 print 'F';
03 if (a <= 1) return 1;
04 return bar(a, foo(a-1));
05 }
06
07 int bar(int x, int y) {
08 print 'B';
09 if (x > y) return baz(x, y);
10 return baz(y, x);
11 }
12
13 int baz(int x, int y) {
14 print 'Z'
15 if (y == 0) return 0;
16 return baz(x, y-1) + x;
17 }
18
19 void main() {
20 foo(3);
21 }
my question is what tactic will be the best to solve this kind of the questions? I'm not allowed to use PC of course
P.S. You can use eager evaluation as in c++ or normal order evaluation(output will be different of course, but I'm interested in tactics only), I tried to solve it using stack, every time write the function which I call, but anyway it is complicated
thanks in advance for any help
I would use a "bottom-to-top" attempt:
baz is the function that is called, but doesn't call other functions (except itself). It outputs 'Z' exactly y + 1 times, the return code is x*y (you add x after each call).
bar is the "next higher" function, it outputs 'B' once and calls baz with its lower argument as the second parameter - the return code is x*y, too.
foo is the "top" function (right after main) and its the most complicated function. It outputs 'F', not only once, but a times (because of the foo(a-1) at the end that is evaluated before the bar call. The bar call multiplies a and foo(a-1), which will multiply a-1 and foo(a-2) and so on, until foo(1) is evaluated and returns 1. So the return code is a * (a-1) * ... 2 * 1, so a!.
This is not a complete analysis, f.e. we don't know in which order the characters will be output, but it is a rough scheme of what happens - and as you and other people in the comments pointed out, this is what you want - tactics instead of a complete answer.
What I'd probably do is to start with the main() function at the top left corner of the page, write down the first line executed, keeping track of local variables etc., then write the next line under it and so on.
But when a function is called, also move right by one column, writing down the function's name and the actual value of the input arguments for that invocation first and then proceding with the lines in that function.
When you return from the function, move left and write the return value between the two columns.
Also, keep a separate area for the "standard output", where all the printed text goes.
These steps should take you through most of "think like a computer" problems.

Using C++ libraries in an R package

What is the best way to make use of a C++ library in R, hopefully preserving the C++ data structures. I'm not at all a C++ user, so I'm not clear on the relative merits of the available approaches. The R-ext manual seems to suggest wrapping every C++ function in C. However, at least four or five other means of incorporating C++ exist.
Two ways are packages w/ similar lineage, the Rcpp (maintained by the prolific overflower Dirk Eddelbuettel) and RcppTemplate packages (both on CRAN), what are the differences between the two?
Another package, rcppbind available, on R forge that claims to take a different approach to binding C++ and R (I'm not knowledgeable to tell).
The package inline available on CRAN, claims to allow inline C/C++ I'm not sure this differs from the built in functionality, aside for allowing the code to be inline w/R.
And, finally RSwig which appears to be in the wild but it is unclear how supported it is, as the author's page hasn't been updated for years.
My question is, what are the relative merits of these different approaches. Which are the most portable and robust, which are the easiest to implement. If you were planning to distribute a package on CRAN which of the methods would you use?
First off, a disclaimer: I use Rcpp all the time. In fact, when (having been renamed by the time from Rcpp) RcppTemplate had already been orphaned and without updates for two years, I started to maintain it under its initial name of Rcpp (under which it had been contributed to RQuantLib). That was about a year ago, and I have made a couple of incremental changes that you can find documented in the ChangeLog.
Now RcppTemplate has very recently come back after a full thirty-five months without any update or fix. It contains interesting new code, but it appears that it is not backwards compatible so I won't use it where I already used Rcpp.
Rcppbind was not very actively maintained whenever I checked. Whit Armstrong also has a templated interface package called rabstraction.
Inline is something completely different: it eases the compile / link cycle by 'embedding' your program as an R character string that then gets compiled, linked, and loaded. I have talked to Oleg about having inline support Rcpp which would be nice.
Swig is interesting too. Joe Wang did great work there and wrapped all of QuantLib for R. But when I last tried it, it no longer worked due to some changes in R internals. According to someone from the Swig team, Joe may still work on it. The goal of Swig is larger libraries anyway. This project could probably do with a revival but it is not without technical challenges.
Another mention should go to RInside which works with Rcpp and lets you embed R inside of C++ applications.
So to sum it up: Rcpp works well for me, especially for small exploratory projects where you just want to add a function or two. It's focus is ease of use, and it allows you to 'hide' some of the R internals that are not always fun to work with. I know of a number of other users whom I have helped on and and off via email. So I would say go for this one.
My 'Intro to HPC with R' tutorials have some examples of Rcpp, RInside and inline.
Edit: So let's look at a concrete example (taken from the 'HPC with R Intro' slides and borrowed from Stephen Milborrow who took it from Venables and Ripley). The task is to enumerate all possible combinations of the determinant of a 2x2 matrix containing only single digits in each position. This can be done in clever vectorised ways (as we discuss in the tutorial slides) or by brute force as follows:
#include <Rcpp.h>
RcppExport SEXP dd_rcpp(SEXP v) {
SEXP rl = R_NilValue; // Use this when there is nothing to be returned.
char* exceptionMesg = NULL; // msg var in case of error
try {
RcppVector<int> vec(v); // vec parameter viewed as vector of ints
int n = vec.size(), i = 0;
if (n != 10000)
throw std::length_error("Wrong vector size");
for (int a = 0; a < 9; a++)
for (int b = 0; b < 9; b++)
for (int c = 0; c < 9; c++)
for (int d = 0; d < 9; d++)
vec(i++) = a*b - c*d;
RcppResultSet rs; // Build result set to be returned as list to R
rs.add("vec", vec); // vec as named element with name 'vec'
rl = rs.getReturnList(); // Get the list to be returned to R.
} catch(std::exception& ex) {
exceptionMesg = copyMessageToR(ex.what());
} catch(...) {
exceptionMesg = copyMessageToR("unknown reason");
}
if (exceptionMesg != NULL)
Rf_error(exceptionMesg);
return rl;
}
If you save this as, say, dd.rcpp.cpp and have Rcpp installed, then simply use
PKG_CPPFLAGS=`Rscript -e 'Rcpp:::CxxFlags()'` \
PKG_LIBS=`Rscript -e 'Rcpp:::LdFlags()'` \
R CMD SHLIB dd.rcpp.cpp
to build a shared library. We use Rscript (or r) to ask Rcpp about its header and library locations. Once built, we can load and use this from R as follows:
dyn.load("dd.rcpp.so")
dd.rcpp <- function() {
x <- integer(10000)
res <- .Call("dd_rcpp", x)
tabulate(res$vec)
}
In the same way, you can send vectors, matrics, ... of various R and C++ data types back end forth with ease. Hope this helps somewhat.
Edit 2 (some five+ years later):
So this answer just got an upvote and hence bubbled up in my queue. A lot of time has passed since I wrote it, and Rcpp has gotten a lot richer in features. So I very quickly wrote this
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::IntegerVector dd2(Rcpp::IntegerVector vec) {
int n = vec.size(), i = 0;
if (n != 10000)
throw std::length_error("Wrong vector size");
for (int a = 0; a < 9; a++)
for (int b = 0; b < 9; b++)
for (int c = 0; c < 9; c++)
for (int d = 0; d < 9; d++)
vec(i++) = a*b - c*d;
return vec;
}
/*** R
x <- integer(10000)
tabulate( dd2(x) )
*/
which can be used as follows with the code in a file /tmp/dd.cpp
R> Rcpp::sourceCpp("/tmp/dd.cpp") # on from any other file and path
R> x <- integer(10000)
R> tabulate( dd2(x) )
[1] 87 132 105 155 93 158 91 161 72 104 45 147 41 96
[15] 72 120 36 90 32 87 67 42 26 120 41 36 27 75
[29] 20 62 16 69 19 28 49 45 12 18 11 57 14 48
[43] 10 18 7 12 6 46 23 10 4 10 4 6 3 38
[57] 2 4 2 3 2 2 1 17
R>
Some of the key differences are:
simpler build: just sourceCpp() it; even executes R test code at the end
full-fledged IntegerVector type
exception-handling wrapper automatically added by sourceCpp() code generator