Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide an interface that mimics Python's enumerate() or Go's range() #8

Open
aary opened this issue Aug 24, 2017 · 0 comments
Open
Assignees

Comments

@aary
Copy link
Owner

aary commented Aug 24, 2017

The goal is to copy Python's enumerate() utility

range = [1, 2, 3, 4]
for element, index in enumerate(range):
    print index + " : " + element

or Go's range keyword

for index, element := range someSlice {
    fmt.Println(index, element)
}

In C++ this might look like the following

auto vec = std::vector<int>{1, 2, 3, 4};
for (auto [element, index] : sharp::enumerate(vec)) {
    cout << index << " : " << element << endl;
}

This code will work in C++17 with structured bindings, but will not work with C++14. The closest behavior in C++14 is with std::tie()

auto range = std::vector<int>{1, 2, 3, 4};
auto integer = int{};
auto index = std::size_t{};
for (std::tie(integer, index) : sharp::enumerate(range)) {
    cout << index << " : " << element << endl;
}

This is also fine till support for C++17 is common. Then it will be easy to switch to the nice structured bindings syntax.

@aary aary assigned aary and PrithMDP and unassigned aary Aug 24, 2017
@aary aary changed the title Provide an interface that mimics Python's enumerate() Provide an interface that mimics Python's enumerate() or Go's range() Aug 25, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants