c++ – vector vs string[] when passing to function

c++ – vector vs string[] when passing to function

Use a std::vector< std::string > and pass it by reference if you need to change its contents, const reference if you dont need to change them. This is the simplest, most flexible, and clearest way.

Thus:

void inspectDetails( std::vector< std::string > & details );

std::vector< std::string > details = { Name,Height,Weight };
inspectDetails( details );

cf. http://en.cppreference.com/w/cpp/container/vector

Passing by const reference is an option. This is what a possible program might look then:

#include <iostream>
#include <string>
#include <vector>

void inspectDetails( const std::vector<std::string> & details )
{
    int v = details.size();
    std::cout<<v<<std::endl;
}

int main()
{
    std::vector<std::string> details = {name, height, weight};

    inspectDetails(details);

    return 0;
}

c++ – vector vs string[] when passing to function

Rob K answered right to you question. I will add that sometimes its usefull to use std::array rather than a simple array : http://en.cppreference.com/w/cpp/container/array For example, you can easily know the size of your array.

Leave a Reply

Your email address will not be published. Required fields are marked *