【发布时间】:2021-12-23 02:38:54
【问题描述】:
例如,如果我有一个需要 std::pair 或 std::array 的函数,我可以执行以下操作:
#include <array>
#include <string>
void foo(std::array<int,5>){}
void bar(std::pair<int,std::string>){}
int main(){
foo({1,2,3,4,5});
bar(std::make_pair(1, "test"));
}
将std::vector 作为参数传递的类似方法是什么?
有没有办法将在同一行中创建的 std::vector 传递给期望它作为参数的函数的调用?
如何通过以下方式实现要求:
#include <vector>
#include <string>
void testVector(std::vector<std::string> &t){}
int main(){
std::vector<std::string> boring; // I don't want to create a vector like this
testVector(boring); // this works obviously
testVector({"hello"}); // this does not work
testVector(std::vector<std::string>(){"test"}); // does not work either
}
我刚刚编辑了这个问题,因为我想传递一个参考。但我认为没有办法传递对以这种方式实例化的向量的引用吗?
【问题讨论】:
-
如果你去掉
(),你的最后一个例子应该可以工作;他们根本没有生意。您的倒数第二个示例也应该有效。 -
godbolt.org/z/drdTYjd41 您可以清楚地看到最后两个示例运行良好。最后一个需要修复错误的语法。它适用于 C++11 及更高版本。
-
修复代码中三个明显的拼写错误(缺少
#include <string>,返回类型main,以及额外的())your code builds fine。如果您有问题,请尝试创建一个正确的minimal reproducible example 向我们展示,并从所示示例中复制粘贴完整和完整的构建输出。并告诉我们您正在使用什么编译器,以及您传递给它的标志/选项。 -
对于以后的问题,请记住minimal reproducible example 和它的构建输出。也请花点时间刷新the help pages,取SOtour,阅读How to Ask,以及this question checklist。