在 C 基于范围的 for 循环中获取当前元素的索引

新手上路,请多包涵

我的代码如下:

 std::cin >> str;
for ( char c : str )
    if ( c == 'b' ) vector.push_back(i) //while i is the index of c in str

这是可行的吗?或者我将不得不使用老式的 for 循环?

原文由 Shane Hsu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

假设 strstd::string 或其他具有连续存储的对象:

 std::cin >> str;
for (char& c : str)
    if (c == 'b') v.push_back(&c - &str[0]);

原文由 Benjamin Lindley 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以在 c++11 中使用 lambda:

 #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>

using namespace std;

int main() {
    std::string str;
    std::vector<char> v;
    auto inserter = std::back_insert_iterator<decltype(v)>(v);

    std::cin >> str;
    //If you don't want to read from input
    //str = "aaaaabcdecccccddddbb";

    std::copy_if(str.begin(), str.end(), inserter, [](const char c){return c == 'b';});

    std::copy(v.begin(),v.end(),std::ostream_iterator<char>(std::cout,","));

    std::cout << "Done" << std::endl;

}

原文由 Joel 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题