Reputation: 17
I want to separate in this way a -> num
and b -> num2
But I can’t add another part of the variable to the for loop, for (auto& i, i2 : arr, arr2)
Are there other ways to do this?
#include <charconv>
int64_t a = 123567893,
b = 85162,
test = 0,
test2 = 0;
string arr = to_string(a),
arr2 = to_string(b),
num,
num2 ;
for (auto& i : arr, arr2)
{
num.push_back(i);
num2.push_back(i);
cout << i;
// cout << i2;
}
from_chars(num.data(), num.data() + num.size(), test);
from_chars(num2.data(), num2.data() + num2.size(), test2);
cout << "\n" << test << endl;
cout << "\n" << test2 << endl;
Upvotes: 0
Views: 137
Reputation: 16449
You can use boost
#include <boost/range/combine.hpp>
#include <iostream>
#include <vector>
using namespace std;
int main() {
std::string arr = "ABC";
std::string arr2 = "XYZ";
std::string num, num2;
assert(arr.size() == arr2.size());
for (const auto &i : boost::combine(arr, arr2)) {
decltype(arr)::value_type a;
decltype(arr2)::value_type b;
boost::tie(a, b) = i;
num.push_back(a);
num2.push_back(b);
cout << a;
cout << b;
}
}
Output is
AXBYCZ
I don't know if there is a solution for range-based for loops without boost . Of course, you could
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
std::string arr = "ABC";
std::string arr2 = "XYZ";
std::string num, num2;
for (unsigned int i{0}; i < std::max(arr.size(), arr2.size()); ++i) {
if (i < arr.size()) num.push_back(arr[i]);
if (i < arr2.size()) num2.push_back(arr2[i]);
if (i < arr.size()) cout << arr[i];
if (i < arr2.size()) cout << arr2[i];
}
}
Upvotes: 2
Reputation: 2933
Why not this
for_each(arr.begin(),arr.end(), [&num](char c) {num.push_back(c);})
for_each(arr2.begin(),arr2.end(), [&num](char c) {num.push_back(c);})
Upvotes: -1
Reputation: 16876
This here
for (auto& i : arr, arr2)
Won't work because that's not what the comma operator does. You can read about the comma operator here. In short, arr, arr2
returns arr2
so for (auto& i : arr, arr2)
is equivalent to for (auto& i : arr2)
.
Instead, since arr
and arr2
are std::string
, you can just concatenate them with +
:
for (auto& i : arr + arr2)
{
num.push_back(i);
}
Upvotes: 1