I need to create a code that will extract the odd positions and return the even postions, so for this code, i need it to return "bd" can anyone point me in the right direction to fix this code so it gives me the output i need? Please note that the main function cannot be changed
string myFunction1(string str) {
string result = "";
for(int i=1; i<str.length();i =2) {
result = str[i];
}
return result;
}
int main(){
assert(myFunction1("abcde").compare("bd") == 0);
}
CodePudding user response:
Use Range-v3
#include <iostream>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/chunk.hpp>
#include <range/v3/view/transform.hpp>
#include <range/v3/view/drop.hpp>
#include <range/v3/view/join.hpp>
#include <string>
using ranges::to;
using namespace ranges::views;
std::string myFunction1(std::string str) {
return str // "abcde", which is [a, b, c, d, e]
| chunk(2) // [[a,b], [c,d], [e]]
| transform(drop(1)) // [[b], [d], []]
| join // [b, d]
| to<std::string>; // "bd"
}
int main () {
assert(myFunction1("abcde").compare("bd") == 0);
}
- the syntax
x | f(y)
meansf(x, y)
s
, the string, can be seen as a "range" of letters;chunk(2)
chunks the input range in chunks of 2 (except that the last chunk has one element if the original string as an odd number of characters)transform(f)
appliesf
to every chunk- but
f
isdrop(1)
which drops first element/letter of each chunk, leaving only the second elment/letter, thus resulting in a range of singleton ranges (the last can be empty if the original string as an odd number of characters) join
joins together the singleon-or-empty ranges into a single range.
This is a solution composed of existing and well tested abstractions, not cluttered with low level details. Understanding and learning to write code like this will pay off.
CodePudding user response:
I have noticed that .length()
causes errors sometimes, try to use .size()
instead.
By the way, your code is good, and it should work.
Anyway, try to call the function in the main
just to see what's wrong.
Also, you could make the loop go from 1 to str.size()
and check if(i%2)
then result = str[i]
.
I think it's better to put return 0;
at the end of main
as well.