简体   繁体   中英

Why doesn't the push_back function accept the value/parameter?

I am trying to store some specific characters of a string in a vector. When I want to push back the characters though, there is a problem with the value and I do not know why. Going over the cpp reference page didn't help me unfortunately. Could someone please help? Here is the code:

int main()
{
    std::string str1 = "xxxGGxx$xxxGxTxGx";

    std::vector<std::string> vec;
    std::vector<std::string>::iterator it;
    
    for(auto &ch:str1)
    {
        if(ch == 'G' || ch == '$' || ch == 'T')
        {
            vec.push_back(ch); //Problem: ch not accepted 
        }
    }
    
    for(it = vec.begin(); it!=vec.end(); it++)
    {
        std::cout << *it;
    }
    
    
}

Vector 需要是char类型,而不是string类型。

The reason vec.push_back(ch); does not work is because vec is a vector of strings and not a vector of char. push_back() only accepts the type stored inside the vector, in this case string. A vector<int> cannot push_back a string because a string can't be implicitly converted to an int. It has to somehow be converted to an int first then pushed back. Since a char can't be implicitly converted into a string the compiler gets confused and thinks its impossible.

There are two simple alternatives:

  1. Instead of using vector<string> use vector<char> that way push_back() will append characters.
    vector<char> vec;
    char ch = 'a';
    vec.push_back(ch);  // both these work
    vec.push_back('b'); // both these work
  1. Or, Convert your char into a string and then call push_back onto your string.
string str(1, ch);  // Creates a string containing 1 character equal to ch
vec.push_back(str); // Push back our 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