Write your question here.

Is there a way to add all the elements of a vector to an integer sequentially?
So...the vector has 1, 2, and 3
The integer is 10
The result should be 11, 12, and 13

As a side note, is there a way to add a repeating number to an integer to infinity?
Example...the integer is 10 and I want to add 4 to it. Then 4 again. And again. And again in a loop
Last edited on
Do you want the result to be another vector with the values 11, 12, 13, the same vector with the values changed to 11, 12, 13 or just iterate over the vector and show the values with 10 added??

Add.... Yes - but not to infinity as such but to the maximum value allowed for the type used (eg unsigned int 2^32). Just use a simple for loop without a terminating condition. A for loop has 3 parts separated by ; All parts are optional.

Do you mean something like this:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main() {
	const std::vector v { 1, 2, 3 };
	std::vector<int> n;

	std::ranges::transform(v, std::back_inserter(n), [](auto i) {return i + 10; });
	std::ranges::copy(n, std::ostream_iterator<int>(std::cout, " "));

which displays:

11 12 13

Last edited on
valarray has some tricks that may work for you.
it would be alonng the lines of valarray<int> v {1,2,3} ... v+= 10 ... then v holds 11,12,13

for the number, you can add 4 to it of course, every time.
you can make an object such that every time it is referenced, it adds 4 to it, if you want to get snarky.
Last edited on
Topic archived. No new replies allowed.