#include <string>
#include <algorithm>
void doSomething( const char& );
int main() {
std::string alphabet = "abcdefghijklmnopqrstuvwxyz";
std::for_each( alphabet.begin(), alphabet.end(), &doSomething);
}
或者
#include <string>
#include <boost/foreach.hpp>
int main() {
std::string alphabet = "abcdefghijklmnopqrstuvwxyz";
BOOST_FOREACH( char c, alphabet) {
//do something
}
}
使用 C++2011
#include <string>
#include <algorithm>
int main() {
std::string alphabet = "abcdefghijklmnopqrstuvwxyz";
std::for_each( alphabet.begin(), alphabet.end(),[](const char& c){ /*do something*/} );
}
甚至
#include <string>
int main() {
std::string alphabet = "abcdefghijklmnopqrstuvwxyz";
for( char c : alphabet) {
//do something
}
}
编辑:您在编辑中提到希望它在嵌入式环境中工作
int main() {
const char* alphabet = "abcdefghijklmnopqrstuvwxyz";
for( char* ptr = alphabet; *ptr!='\0'; ++ptr) {
//do something (*ptr)
}
}
编辑2:
如果您知道您使用的是 ASCII 之类的东西
int main() {
for( char l = 'a'; l<='z'; ++l) {
//do something (l)
}
}