c++ - Finding the index of a string inside a field of strings -
my apologies basic question, i'm new rcpp , c++ r.
i have field (arma::field
) have initialized hold strings (arma::field<std::string> my_vector
). have string std::string id
somewhere inside field of strings, , find position of is. i'm used doing vectors , numbers similar below:
arma::vec fun(arma::vec input_vector){ // find vector equals 5 (for example) uvec index = arma::find(input_vector == 5); return index; }
i tried exact same thing, given string instead of number compare:
arma::uvec fun(arma::vec input_vector, std::string id){ // find vector string id uvec index = arma::find(input_vector == id); return index; }
this returns error
error: invalid operands binary expression ('arma::vec' (aka 'col<double>') , 'std::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >'))
which made sense because vector not initialized contain strings. though don't think vector can initialized contain strings, because when tried arma::vec<std::string>
, gives mess of errors.
this lead me fields can hold lot more kinds of variables.
arma::uvec fun(arma::field<std::string> input_field, std::string id){ // find vector equals 5 (for example) uvec index = arma::find(input_field == id); return index; }
however returns
error: invalid operands binary expression ('arma::field<std::string>' , 'std::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >'))
i have tried strcmp
well, threw error
error: no viable conversion 'arma::field<std::string>' 'const char *'
this leads me ask, how can find position of string within field?
i'm open changing types around works better, suspect using std::vector
might work better or perhaps different kind haven't heard of. however, first experiments haven't been successful. if has hints on direction go, appreciated.
edit: clarified find
arma::find
instead of std::find
not clear.
arma
not support storage of std::string
within data structures per matrix types
the root matrix class mat, type 1 of:
- float, double, std::complex, std::complex, short, int, long, , unsigned versions of short, int, long
in turn, rcpp
not support import or export of std::vector<std::string>
armadillo
. thus, error.
the easiest way find string in case loop through vector , check each element. alternatively, make map , see if key within map.
loop string checking approach:
#include <rcpp.h> // [[rcpp::export]] std::vector<int> find_string_locs(std::vector<std::string> input_vector, std::string id) { std::vector<int> id_locs; // setup storage found ids for(int =0; < input_vector.size(); i++) // loop through input if(input_vector[i] == id) // check if input matches target id_locs.push_back(i); return id_locs; // send locations r (c++ index shift!) } /***r input_vector = c("stat","toad","stat","rcpp") id = "stat" find_string_locs(input_vector,id) */
the output then:
[1] 0 2
note c++ index shift... starts @ 0 instead of 1 in r.
Comments
Post a Comment