本文介绍了向量字符串push_back在C ++中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码段接收字符串,定界符(空格)和vector作为参数,并根据定界符分割字符串并将其存储在vector中。如果我使用push_back,它不会将任何内容存储到向量中,但是如果我使用[]运算符,则可以工作。有人可以解释为什么push_back不起作用吗?

This code snippet receives string, delimiter(space) and vector as argument and splits the string according to delimiter and stores it in vector. It is not storing anything into vector if i use push_back but works if i use [] operator. Can someone explain why push_back is not working?

void split(const string & input,char delim,vector<string> & elems){
    stringstream  ss;
    ss.str(input);
    string item;
    int i = 0;
    while(getline(ss,item,delim)){
        //elems.push_back(item);
        elems[i] = item;
        i++;
    }
}

int main(){
   char delim = ' ';
   vector<string> item(2);
   string input;
   getline(cin,input);
   split(input,delim,item);
}


推荐答案

如果您已为向量分配了一定的大小(n),然后pushback(item)将项目放在索引n处,并将向量调整为更大的大小。如果您知道到期的字符串数,那么无论如何,在分配大小为n后,都应该使用 elems [i] = item;

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.

如果您不知道传入的计数,但是知道它会大于n,则不要预分配。相反,使用 elems.reserve(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);

然后使用 elems .push_back(item);

这篇关于向量字符串push_back在C ++中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 04:23