vector string push_back is not working in c++(向量字符串 push_back 在 C++ 中不起作用)
问题描述
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);
}
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);
这篇关于向量字符串 push_back 在 C++ 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:向量字符串 push_back 在 C++ 中不起作用


基础教程推荐
- 用指数格式表示浮点数 1970-01-01
- C++:为什么结构类需要一个虚拟方法才能成为多态? 2022-10-19
- C语言3个整数的数组 1970-01-01
- C语言数组 1970-01-01
- C++多态 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 向量<unique_ptr<A>>使用初始化列表 2022-10-23
- 迭代std :: bitset中真实位的有效方法? 2022-10-18
- 总计将在节日礼物上花多少钱 1970-01-01
- 对 STL 容器的安全并行只读访问 2022-10-25