std::string mstring[5];
mstring[0] = "veena";
mstring[1] = "guitar";
mstring[2] = "sitar";
mstring[3] = "sarod";
mstring[4] = "mandolin";
I want to assign the array like above. I don't want to do it at initialization but assign later. Is there a way to combine 5 statements into one.
CodePudding user response:
You can do that by using std::array<std::string, 5>
instead of the raw array.
For example
#include <iostream>
#include <string>
#include <array>
int main()
{
std::array<std::string, 5> mstring;
mstring = { "veena", "guitar", "sitar", "sarod", "mandolin" };
for ( const auto &s : mstring )
{
std::cout << s << ' ';
}
std::cout << '\n';
}
The program output is
veena guitar sitar sarod mandolin
Another approach when a raw array is used is to use std::initializer_list
in range-based for loop. For example
#include <iostream>
#include <string>
int main()
{
std::string mstring[5];
size_t i = 0;
for ( auto s : { "veena", "guitar", "sitar", "sarod", "mandolin" } )
{
mstring[i ] = s;
}
for ( const auto &s : mstring )
{
std::cout << s << ' ';
}
std::cout << '\n';
}
The program output is the same as shown above
veena guitar sitar sarod mandolin
If your compiler supports C 20 then instead of these statements
size_t i = 0;
for ( auto s : { "veena", "guitar", "sitar", "sarod", "mandolin" } )
{
mstring[i ] = s;
}
you can use just one range-based for loop
for ( size_t i = 0; auto s : { "veena", "guitar", "sitar", "sarod", "mandolin" } )
{
mstring[i ] = s;
}
CodePudding user response:
This is a two-liner, but I think one-lining is not possible with native arrays (at least to my best knowledge).
- Initialize a temporary array with the desired values
- swap pointers with the original array
In that way you can use the one-line initialization for arrays, but still can manipulate the original array before setting the values.
#include <string>
#include <iostream>
int main(){
std::string mystring[5];
std::string tmp[5] = {"veena","guitar","sitar", "sarod", "mandolin"};
std::swap(mystring, tmp);
for(auto& s : mystring) std::cout << s << std::endl;
return 0;
}
CodePudding user response:
You can use comma operator to combine multiple expressions into one statement.
mstring[0] = "veena",
mstring[1] = "guitar",
mstring[2] = "sitar",
mstring[3] = "sarod",
mstring[4] = "mandolin";