'Get index of current element in C++ range-based for-loop
My code is as follows:
std::cin >> str;
for ( char c : str )
if ( c == 'b' ) vector.push_back(i) //while i is the index of c in str
Is this doable? Or I will have to go with the old-school for loop?
Solution 1:[1]
Maybe it's enough to have a variable i?
unsigned i = 0;
for ( char c : str ) {
if ( c == 'b' ) vector.push_back(i);
++i;
}
That way you don't have to change the range-based loop.
Solution 2:[2]
The range loop will not give you the index. It is meant to abstract away such concepts, and just let you iterate through the collection.
Solution 3:[3]
What you are describing is known as an 'each with index' operation in other languages. Doing some quick googling, it seems that other than the 'old-school for loop', you have some rather complicated solutions involving C++0x lambas or possibly some Boost provided gems.
EDIT: As an example, see this question
Solution 4:[4]
You can use lambdas in c++11:
#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;
}
Solution 5:[5]
In C++ 20, I use initializer like this:
for(unsigned short i = 0; string item : nilai){
cout << i << "." << "address " << &item << " -> " << item << endl;
i++;
}
So, your case will be like:
for (unsigned short i = 0; char c : str ) {
if ( c == 'b' ) vector.push_back(i);
++i;
}
I don't know what 'vector' mean in your case, and what is push_back().
Don't forget to add -std=c++20 (I just use g++ for compiling, so i don't know much about other compiler). You can also start the 'i' value from 1 if you want to. I think it's elegant enough
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniel Frey |
| Solution 2 | Karthik T |
| Solution 3 | Community |
| Solution 4 | jogojapan |
| Solution 5 |
