如何将字符串添加到 C++ 中的字符串向量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23538567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add string to vector of string in C++
提问by farahm
I have:
我有:
vector<string> *history;
history = new vector<string>[300];
where history should contain several strings (up to 300).
其中 history 应包含多个字符串(最多 300 个)。
Then I do in order to add a string:
然后我这样做是为了添加一个字符串:
std::stringstream sstm;
sstm << frameProc << " ";
string result = sstm.str();
history[xyz]= result; //This line does not work
But that does not work. How should I do this?
但这不起作用。我该怎么做?
回答by juanchopanza
You are dynamically allocating an array of vector<string>
here:
您在vector<string>
这里动态分配一个数组:
vector<string> *history;
history = new vector<string>[300];
What you really need is a vector of strings:
你真正需要的是一个字符串向量:
std::vector<std::string> history;
std::stringstream sstm;
sstm << frameProc << " ";
std::string result = sstm.str();
history.push_back(result);
回答by Vlad from Moscow
If to answer your question
如果要回答你的问题
How to add string to vector of string in C++
如何将字符串添加到 C++ 中的字符串向量
then it is done the following way
然后按以下方式完成
std::vector<std::string> v;
v.push_back( "Some string" );
or
或者
v.insert( v.end(), "Some string" );
If to consider your code snippet then the correct statement will look
如果考虑您的代码片段,那么正确的语句将看起来
history[xyz].push_back( result );
or
或者
history[xyz].insert( history[xyz].end(), result );
EDIT:
编辑:
Also I thought that maybe you are doing something wrong do not understanding what you are doing. Then consider the following code. Maybe it will be helpfull.
我还想,也许你做错了什么,不明白你在做什么。然后考虑下面的代码。也许它会有所帮助。
std::vector<std::string> history( 300 );
//...
history[xyz] += result;