Is there a way to add all the elements of a vector to an integer sequentially?
-
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
-
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
puckettrobinson675 wrote:
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
Yes, just add 4 in the loop. however, not infinitely but until your integer exceeds the possible nax value for its type. See [C and C++ Integer Limits | Microsoft Learn](https://learn.microsoft.com/en-us/cpp/c-language/cpp-integer-limits?view=msvc-170)
-
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
-
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
Quote:
Is there a way to add all the elements of a vector to an integer sequentially?
Yes, there are, at least, three different ways:
#include #include #include using namespace std;
void dump (vector v)
{
for (auto x :v )
cout << x << " ";
cout << "\n";
}int main()
{{ // method 1: access items by indices
vector v{1,2,3};int c = 4; for (size\_t n = 0; n v{1,2,3}; int c = 4; for (auto & x : v) { x += c; } cout << "method 2: "; dump(v);
}
{ // method 3: use 'transform' of the algorithm library
vector v{1,2,3};int c = 4; transform(v.begin(), v.end(), v.begin(), \[=\](int x){ return x+c; }); cout << "method 3: "; dump(v);
}
}Quote:
As a side note, is there a way to add a repeating number to an integer to infinity?
Yes, but this way the addition will overflow. Try:
#include using namespace std;
int main()
{
int i = 1;
int last_i;
int c = 4;
for (;;)
{
last_i = i;
i += c;
if ( i < last_i)
break;
}cout << "unfortunately, (" << last_i << "+" << c << ") makes " << i;
}"In testa che avete, Signor di Ceprano?" -- Rigoletto