C++ C++;无法打印字符串元素的向量
为什么我不能打印向量的第三个元素? 我需要一个单词,它将被分成向量,然后,它们将被打印出来。 但是向量的第三个元素没有显示在终端中C++ C++;无法打印字符串元素的向量,c++,vector,C++,Vector,为什么我不能打印向量的第三个元素? 我需要一个单词,它将被分成向量,然后,它们将被打印出来。 但是向量的第三个元素没有显示在终端中 #include <iostream> #include <vector> using namespace std; void divideTextCommand(string txt, vector<string> cmd) { string word = ""; for (auto x
#include <iostream>
#include <vector>
using namespace std;
void divideTextCommand(string txt, vector<string> cmd)
{
string word = "";
for (auto x : txt)
{
if (x == ' ')
{
cmd.push_back(word);
word = "";
}
else
{
word = word + x;
}
}
cmd.push_back(word);
}
int main()
{
cout << "Command:" << endl;
string textCommand; getline(cin, textCommand);
vector<string> command;
cout << " " << endl;
divideTextCommand(textCommand, command);
cout << command[2];
return 0;
}
您需要通过引用传递
cmd
:
void divideTextCommand(string txt, vector<string> &cmd)
// ^
void divideTextCommand(字符串txt、向量和cmd)
// ^
实际上,main
中的command
保持为空,因此访问元素[2]是UB
但我更喜欢福克斯先生的建议——在
divideTextCommand
中将单词分割成本地声明的数组,然后作为函数结果返回。它更自然,不会对性能造成任何影响。您需要通过cmd
参照:
void divideTextCommand(string txt, vector<string> &cmd)
// ^
void divideTextCommand(字符串txt、向量和cmd)
// ^
实际上,main
中的command
保持为空,因此访问元素[2]是UB
但我更喜欢福克斯先生的建议——在
divideTextCommand
中将单词分割成本地声明的数组,然后作为函数结果返回。它更自然,不会带来性能损失。您当前没有提供对命令的引用:
void divideTextCommand(string txt, vector<string> cmd)
// ^ this is a copy, original is not edited
void divideTextCommand(字符串txt,向量cmd)
//^这是一份副本,不编辑原件
我建议您只需返回您的命令:
std::vector<std::string> divideTextCommand(std::string txt) {
std::vector<std::string> cmd
...
return cmd; // Thanks to RVO, this is no more expensive and is much clearer.
std::vector divideTextCommand(std::string txt){
std::vector cmd
...
return cmd;//多亏了RVO,这不会更昂贵,而且更清晰。
您当前未提供对以下命令的引用:
void divideTextCommand(string txt, vector<string> cmd)
// ^ this is a copy, original is not edited
void divideTextCommand(字符串txt,向量cmd)
//^这是一份副本,不编辑原件
我建议您只需返回您的命令:
std::vector<std::string> divideTextCommand(std::string txt) {
std::vector<std::string> cmd
...
return cmd; // Thanks to RVO, this is no more expensive and is much clearer.
std::vector divideTextCommand(std::string txt){
std::vector cmd
...
return cmd;//多亏了RVO,这不会更昂贵,而且更清晰。
在您的代码中,在:
void divideTextCommand(string txt, vector<string> cmd)
通过这样做,我们将引用cmd
的地址,并对两个版本进行更改
结果(与您的代码一起,添加&
):
更多信息:
void divideTextCommand(string txt, vector<string> cmd)
通过这样做,我们将引用cmd
的地址,并对两个版本进行更改
结果(与您的代码一起,添加&
):
更多信息:
string textCommand;getline(cin,textCommand);
-为什么这些代码都在一行上?疏远代码的读者不是一种好做法。无关:编写这样的代码会让人(我)陷入嘶嘶的状态:string textCommand;getline(cin,textCommand)
-为什么这些都在一行上?疏远你代码的读者不是好的做法。如果你担心,“天哪!复制向量”
!如此挥霍的费用!知道你不是第一个,因此一些真正聪明的人想出了。@user4581301这些是有史以来最好的补充!强制复制省略或删除(N) RVO.下一步:如果将参数作为返回值传递,则避免将参数复制/移动到函数中-让它成为同一个实体。如果您担心,“天哪!复制向量!这是一笔挥霍的开支!”要知道你不是第一个,因此一些非常聪明的人想出了。@user4581301这些是有史以来最好的添加!强制复制省略或(N)RVO。下一步:如果作为返回值传递,则将参数的复制/移动从复制/移动到函数-让它是同一个实体。