iterate through two std::lists simultaneously

The following function constructs a std::vector<std::byte> object which is used for passing bind-arguments to a Query-object.
Line 4 specifies the variable to which values should be bound. Multiple items may be bound to a value, they are separated by a 0x01 byte. And each item consists of a value-string and a type-specifier (lines 6-8).
Line 10 removes the trailing 0x01.
The function does exactly what is expected.
1
2
3
4
5
6
7
8
9
10
11
12
13
void QueryObject::Bind(const std::string & name, const std::list<std::string> & valueList) {
	std::vector<std::byte> exec, result;
	std::string type { "" };
	pushByte(0x03, exec).addVoid(QueryID, exec).addVoid(name, exec);
	for (std::string val : valueList) {
		addVoid(val, exec);
		addVoid(type, exec);
		pushByte(0x01, exec);
	};
	exec.pop_back();
	handShake(exec, result);
	Response.setValues((std::string) __FUNCTION__, result);
};

This function uses a constant "" for the type, 'addVoid' replaces an empty string by a 0x00.

Is it possible to - after providing a third argument, typeList to the function - to change the loop in such a way that both lists are evaluated simultaneously? (Of course after checking that both lists have the same size).
It's possible but not with range for loop, instead you need the vintage version of the for loop :)

1
2
3
4
5
6
for (auto iter1 = list1.begin(), iter2 = list2.begin();
     (iter1 != list1.end()) && (iter2 != list2.end());
     ++iter1, ++iter2)
{
     // TODO: Insert code here to use iterators to both lists
}


btw: the "vintage" code is how B. Stroustrup calls code which does not use modern language features.
Last edited on
C++23, consider std::ranges::zip_view
1
2
3
4
for(auto [x, y]: std::views::zip(xs, ys))
{
  // ...
}

https://en.cppreference.com/w/cpp/ranges/zip_view
Last edited on
re zip. For an article see https://www.cppstories.com/2023/view-zip/
mbozzi, Awesome solution, that's why I like this site because there's always something new to learn from you guys.
@mbozi
According to https://gcc.gnu.org/projects/cxx-status.html C++23 support in GCC is still experimental but this seems to be what I am looking for!
For implementation, see https://en.cppreference.com/w/cpp/compiler_support

This indicates that GCC supports ranges::zip with v13
Topic archived. No new replies allowed.