我想使用最高评分答案中的字符串拆分函数,该问题的链接如下:Split a string in C++?。以下是方便复制的回答:
我在这里有一个问题。为什么声明是
我有:
那么有什么区别呢?
#include <string>
#include <sstream>
#include <vector>
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
我在这里有一个问题。为什么声明是
std::vector<std::string> &split(...)
而不是void split(...)
?作为参数,我们接收std::vector<std::string> &elems
,这就是我们想要的结果。如果我们接收到一个引用,为什么还需要返回任何东西呢?我有:
int &multA (int &n)
{
n = 5*n;
return n;
}
void multB (int &n)
{
n = 5*n;
}
并且:
int n1, n2;
n1 = 1;
n2 = 1;
cout << "n1: " << n1 << endl;
cout << "n2: " << n2 << endl;
n1 = multA(n1);
multB(n2);
cout << "n1: " << n1 << endl;
cout << "n2: " << n2 << endl;
结果,我有:
n1: 1
n2: 1
n1: 5
n2: 5
那么有什么区别呢?