【问题标题】:C++ pass newly created vector as parameterC ++将新创建的向量作为参数传递
【发布时间】:2021-12-23 02:38:54
【问题描述】:

例如,如果我有一个需要 std::pairstd::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

}

我刚刚编辑了这个问题,因为我想传递一个参考。但我认为没有办法传递对以这种方式实例化的向量的引用吗?

【问题讨论】:

标签: c++ c++11 vector c++17


【解决方案1】:

首先你的入口点是错误的,它应该是int main 而不是void main。以下代码有效

#include <vector>
#include <string>

void testVector(std::vector<std::string>){}

int main()
{

    std::vector<std::string> boring;
    testVector(boring);

    testVector({"hello"}); // This works
    testVector(std::vector<std::string>{"test"}); // This works too :)
}

Here is the test of the above code

【讨论】:

  • OP最近更改了他/她的问题的详细信息,因此您可以考虑编辑您的帖子。
  • 对不起,我有点匆忙回答这个问题。如果有重复,我会编辑/删除它
  • @justANewbie 我是这篇文章的 OP
  • @L.Gashi 哎呀。对不起这个错误。你可以说我对你的评论有点匆忙:)
【解决方案2】:

使用

void baz(std::vector<int> vec) { … }

作品:

…
baz({1,2,3});
…

但是:使用纯向量作为签名将导致每个函数调用都生成向量的副本。除非您的方法出于某种原因实际上需要副本,否则您很少真正需要它。

通常的方法是使用引用:

void baz_ref(std::vector<int>& vec) { … }

这意味着现在,该函数不会获得副本,而是在原始向量上工作 - 但这意味着您的函数可能具有调用函数未预料到的副作用

此外,您不能调用baz_ref({1, 2, 3});,因为这会传递对临时对象的引用。

如果您的函数不需要修改向量:

void baz_constref(const std::vector<int>& vec) { … }

是要走的路——没有副本,试图修改vec 是行不通的。编译器可以很好的优化这个,你也可以调用baz_constref({1, 2, 3});

还有另一种选择:移动语义,如果您的函数实际上修改了向量,它可能是正确的——该函数是否应该成为新的“所有者”?然后,您应该将该向量移动到函数中,但调用函数随后将失去使用它的能力。

【讨论】:

    猜你喜欢
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 2016-01-12
    相关资源
    最近更新 更多