How can I pass a vector variable to a function?

后端 未结 3 1291
一向
一向 2021-01-28 10:17

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 argume

3条回答
  •  -上瘾入骨i
    2021-01-28 11:01

    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 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::iterator i = v.begin(); i != v.end(); ++i)
        the_function(*i);
    

    EDIT: 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& v)
    {
        // can access v in here, e.g. to print...
        std::cout << "[ (" << v.size() << ") ";
        for (std::vector::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]);
    

    or

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

    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';
    }
    

    (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).

提交回复
热议问题