嗨,我正在尝试更改作为引用传递的vec的内容,我对这个概念非常陌生,无法看出我的代码有什么问题:
std::string pluralize(std::string const& word) {
if (uncountables.count(word) > 0) {
return word;
}
for (auto const& r : rules) {
if (r.matches(word)) {
return r.pluralize(word);
}
}
// The last rule is fully generic "append s" rule, so we cannot
// get here unless something is seriously wrong.
throw std::runtime_error("Word '" + word + "' did not match any rule");
}
std::vector<std::string> pluralize(std::vector<std::string> const& words) {
for (auto word : words) {
word = pluralize(word);
std::cout << word << " word from pluralize called with vec" << std::endl;
}
std::cout << words[0] << " 0 word from pluralize called with vec" << std::endl;
std::cout << words[1] << " 1 word from pluralize called with vec" << std::endl;
return words;
}当以字符串作为参数调用方法复数时,它将按预期的方式工作:更改传递的word的值。当使用vec调用时,它不会更改传递的字符串的值。这些是我的测试用例:
对于这些测试用例,代码可以正常工作:
SECTION("Respects capitalization") {
REQUIRE(pluralize("Car") == "Cars");
REQUIRE(pluralize("Mouse") == "Mice");
REQUIRE(pluralize("German") == "Germans");
}这些测试用例失败:
REQUIRE(
pluralize({"Car", "Mouse", "German"}) == make_vec({"Cars", "Mice", "Germans"})
);发布于 2018-10-23 09:43:21
您不能修改words,因为它是const。
您没有注意到这一点,因为您没有修改它--在for (auto word : words)中推导出来的类型是std::string,而不是std::string&。
例如,您可以复制输入并修改副本:
std::vector<std::string> pluralize(std::vector<std::string> const& words)
{
std::vector<std::string> plurals = words;
for (auto& word : plurals) {
word = pluralize(word);
}
return plurals;
}或者在一个循环中收集多个单词:
std::vector<std::string> pluralize(std::vector<std::string> const& words)
{
std::vector<std::string> plurals;
for (const auto& word : words) {
plurals.push_back(pluralize(word));
}
return plurals;
}或者使用std::transform
std::vector<std::string> pluralize(std::vector<std::string> const& words)
{
std::vector<std::string> plurals;
std::transform(words.begin(), words.end(), std::back_inserter(plurals), pluralize);
return plurals;
}或者其他解决方案..。
发布于 2018-10-23 09:30:46
问题在于:
for (auto word : words) {
word = pluralize(word);
}这里的变量word是一个字符串值。您正在更改该值,但这不会改变向量中的单词。尝试使用引用:
for (auto& word : word) {
word = pluralize(word);
}auto不推导引用。
编辑:,您不能修改向量中的元素,因为可以将它作为对const的引用。解决这个问题的方法之一就是取一份矢量的副本。最简单的方法是修改函数的签名以传递值:
std::vector<std::string> pluralize(std::vector<std::string> words) {
for (auto& word : words) {
word = pluralize(word);
}
return words;
}https://stackoverflow.com/questions/52945088
复制相似问题