I am passing a const reference std::string to a function. I want to iterate over the triples of the string and convert those triples to ints. I do so by bit shifting. My problem is that I do not know how to iterate over the string as I need the element and the index oof the triple in the string.
#include <vector>
#include <string>
unsigned int three_char_to_int(std::string start){
unsigned int substr {0};
substr |= start[0];
substr |= (start[1] << 8);
substr |= (start[2] << 16);
return substr;
}
std::vector<int> test_Function(std::string const& text){
int length = text.length();
std::vector<unsigned int> res = std::vector<unsigned int>(length, 0);
for(int i {0}; i < length-2; ++i){
continue;
// text is not a pointer, so this does not work
// res[i] = three_char_to_int(text +i);
// this does not work either
// res[i] = three_char_to_int(text[i]);
}
}
int main(){
std::string text = {"Hello, World!"};
auto result = test_Function(text);
// do something with result
return 0;
}
I'd be thankful for any hints and solutions. If you have a better idea how to do what I'm trying I'll be happy to see that, too.
Note: I'm learning C++
Assuming you are not interested in refactoring your code considerably to use c++20 or c++23 features, try utilizing
std::vector::emplace_backandstd::string::substr:Output: