Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a array of std::string by reference

Tags:

c++

arrays

string

I'ld like to create a function that passes not a std::string by reference to be modified,

void changeStr(std::string &str)
{
    str = "Hello World!";
}

, but rather an entire, fixed-sized array of std::strings (the function will do exactly the same: attribute some specific strings to each space in the array). But I don't know which is the appropriate syntax...

like image 211
Momergil Avatar asked May 30 '26 04:05

Momergil


1 Answers

Since you're using C++ you probably want to pass a collection of values by reference instead of a collection of references by reference. The easiest way to achieve this is to use std::vector<T>

void changeStr(std::vector<std::string>& collection) { 
  if (collection.size() > 0) {
    collection[0] = "hello world";
  }
}
like image 115
JaredPar Avatar answered Jun 01 '26 18:06

JaredPar