【发布时间】:2019-03-27 10:59:17
【问题描述】:
您好,我正在尝试更改作为参考传递的 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;
}
当使用字符串作为参数调用方法复数时,它按预期工作:更改传递的单词的值。 当使用 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"})
);
【问题讨论】:
标签: c++ string vector reference constants