vector string push_back is not working in c++

跟風遠走 提交于 2019-12-02 11:37:28

If you've pre-allocated the vector with some size (n), then pushback(item) puts item at index n and resizes the vector to an even larger size. If you know the string count due in, then you should use elems[i] = item; anyway after an allocation of size n.

If you don't know the count coming in, but know it's going to be larger than some n, do not pre-allocate. Instead, RESERVE some memory with elems.reserve(n);

Then use elems.push_back(item);

In the main function, please change the declaration of item from

vector<string> item(2);

to

vector<string> item;

And change the split function to use push_back:

void split(const std::string & input,char delim, std::vector<std::string> & elems){
    std::stringstream  ss;
    ss.str(input);
    std::string item;
    int i = 0; // no more required unless for some other purpose
    while(getline(ss,item,delim)){
        elems.push_back(item);
        //elems[i] = item;
        i++; // no more required
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!