我班上有这个功能
bool MyClass::verifyPair(const std::pair<std::string, std::string>& myPair) const { ... };
我需要for循环中的第一个值,但我不想将其用于:
for (int index = 0; index < myPair.first.size(); index++) { ... };
我想使用更新的C ++循环,但是我已经尝试过了,但是没有用:
for (auto& pairIndex : myPair.first) { ... };
答案 0 :(得分:2)
您的“较新的C ++循环”很好,您只是不应该期望得到一个索引,而是一个值:
for (auto& c : myPair.first) {
//do something with 'c' which is a char at a current position
}
换句话说,c
相当于常规for循环中的myPair.first[index]
的值。
答案 1 :(得分:0)
当您在字符串上循环且它是常量时,您应该在foor循环中这样说:
for (auto ch: myPair.first) { ... }
请注意,我更改了变量名称,因为您获得了字符串中的每个字符而不是索引。
如果对象大于char,则可以改用const auto& ch
,但对于字符,最好将其复制。