我的代码如下:
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 许可协议
您可以在 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 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
假设
str
是std::string
或其他具有连续存储的对象: