Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range based for loop, using pointer to string

Tags:

c++

c++11

In the new C++ standard, C++11, one can use range based for loop for processing every character of string.

#include<iostream>
#include<string>

int main()
{
    std::string s1 = "this is an example";
    for (char &c:s1)
        //do any operation
        std::cout<<c;
    return 0;
}

Instead of reference char &c:s1 how can I use a pointer to do that in range based for loop? I want to do something like char *p pointing to s1.

like image 295
ty452567 Avatar asked Dec 09 '25 17:12

ty452567


1 Answers

The range-based for loop will not give you a pointer. However, you can make one:

for (char &c : s) {
    char *p = &c;
}

Or you can do it yourself with a regular loop:

// Note: Requires C++17, where s.data() is relaxed to a char* type.
for (char *p = s.data(), *e = p + s.size(); p != e; p++) {
}

// Pre-C++17 version.
for (char *p = &s[0], *e = p + s.size(); p != e; p++) {
}
like image 191
Dietrich Epp Avatar answered Dec 12 '25 09:12

Dietrich Epp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!