简体   繁体   中英

C++: vector< set<string> > initialization by function

In C++, I would like to initialize a vector of sets of strings by:

string border(getBorder());
vector<string> W(_h_,border+"_"+border);
vector< set<string> > W_f(_h_,getNgrams(&W[0]));

where:

set<string> getNgrams(string word){ ... }

and:

string getBorder(){ ... }

The error message reads:

conversion from 'std::basic_string<char, std::char_traits<char>, std::allocator<char> >*' to non-scalar type 'std::string' requested

You are trying to assign an std::string* to an std::string here:

vector< set<string> > W_f(_h_,getNgrams(&W[0]));

&W[0] is an std::string* , but getNgrams expects an std::string .

set<string> getNgrams(string word){ ... }

your getNgrams function takes a string but you're passing in a string* here:

vector<string> W(_h_,border+"_"+border);
vector< set<string> > W_f(_h_,getNgrams(&W[0])); // look at the argument being passed.

w is a vector<string> , w[0] therefore is a string , and you're passing &w[0] which is a string*

On this line:

vector< set<string> > W_f(_h_,getNgrams(&W[0]));

you get the address of W[0] using the & operator. The type of W[0] is std::string and the type of the address is std::string* (or more specifically, what you see in the error message). You then pass that pointer to the function getNgrams which expects a string instead of a pointer.

Simply remove the & operator to fix. You may wish to use a const reference instead though, to avoid copying the string:

set<string> getNgrams(const string& word)

W[0]产生std::string ,因此&W[0]是指向string的指针,而您有getNgrams(std::string)而不是getNgrams(std::string*) ,因此编译器抱怨从std::string*std::string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM