我如何传递一个矢量变量的函数吗? [英] How can I pass a vector variable to a function?

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

问题描述

我们如何传递矢量变量的函数吗?我有的char *的矢量 和将采取的char *的函数作为参数。我怎样才能通过矢量变量这个功能呢?

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]);

如果你想调用Vector中的每件上的功能,只需循环:

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 ,然后...

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()呼叫中的<$某处C $ C>尝试块或函数直接或间接块中调用)。

(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天全站免登陆