如何将向量变量传递给函数? [英] How can I pass a vector variable to a function?

查看:39
本文介绍了如何将向量变量传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何将vector 变量传递给函数?我有一个 char*vector 和一个将 char * 作为参数的函数.如何将 vector 变量传递给这个函数?

How can we pass vector variables to a function? I have a vector of char* and a function which will take a char * as an argument. How can I pass the vector variable to this function?

推荐答案

如果您有一个接受 char* 参数的函数,那么您只能传递向量中的 char* 之一.例如:

If you have a function taking a char* argument, then you can only pass one of the char* in the vector. For example:

std::vector<char*> v;
char buf[] = "hello world";
v.push_back(buf);
the_function(v[0]);

如果要对向量中的每个成员调用函数,只需循环:

If you want to call the function on each member in the vector, just loop:

for (std::vector<char*>::iterator i = v.begin(); i != v.end(); ++i)
    the_function(*i);

根据您在下面的评论,您实际上想要编写一个接受向量作为参数的函数...尝试:

based on your comment below, you actually want to write a function that accepts the vector as an argument... try:

void the_function(const std::vector<char*>& v)
{
    // can access v in here, e.g. to print...
    std::cout << "[ (" << v.size() << ") ";
    for (std::vector<char*>::iterator i = v.begin(); i != v.end(); ++i)
         std::cout << *i << ' ';
    std::cout << " ]";
}

如果您有一个要调用的现有函数,并且不想更改其参数列表...

If you have an existing function that you want to call, and you don't want to change its argument list...

void TV_ttf_add_row(const char*, const char*, const void*);

...然后,假设您知道向量将有足够的元素:

...then, say you know the vector will have enough elements:

assert(v.size() >= 3); // optional check...
TV_ttf_add_row(v[0], v[1], v[2]);

if (v.size() >= 3)
    TV_ttf_add_row(v[0], v[1], v[2]);

或者,如果您想在 v 中没有足够的元素时抛出异常,那么...

or, if you want an exception thrown if there aren't enough elements in v, then...

try
{
    TV_ttf_add_row(v.at(0), v.at(1), v.at(2));
}
catch (const std::exception& e)
{
    std::cerr << "caught exception: " << e.what() << '\n';
}

(try/catch 块不必包围单个函数调用 - 只要 v.at( ) 调用位于 try 内部的某个位置块或从块内部直接或间接调用的函数).

(the try/catch block doesn't have to surround the single function call - just as long as the v.at( ) calls are somewhere inside the try block or a function directly or indirectly called from inside the block).

这篇关于如何将向量变量传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆