1

I have an std::array<std::string, 4> that I want to use to hold path names for text files that I want to read into the program. So far, I declare the array, and then I assign each std::string object the value.

#include <array>
#include <string>
using std::array;
using std::string;
...
array<string, 4> path_names;
path_names.at(0) = "../data/book.txt";
path_names.at(0) = "../data/film.txt";
path_names.at(0) = "../data/video.txt";
path_names.at(0) = "../data/periodic.txt";

I am using this approach because I know in advance that there are exactly 4 elements in the array, the size of the array will not change, and each path name is hard coded and also cannot change.

I want to declare and initialize the array and all its elements in just one step. For example, this is how I would declare an initialize an array of ints:

array<int, 10> ia2 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};  // list initialization

How would I do the same but for std::string? Creating these strings would involve calling the constructor. It's not as simple as just list-initializing a bunch of ints. How to do that?

Galaxy
  • 2,363
  • 2
  • 25
  • 59

1 Answers1

1

This can be done in two ways:

  1. Using string literals in list initialization

array<string, 4> path_names = {"../data/book.txt", "../data/film.txt", "../data/video.txt", "../data/periodic.txt"};

  1. Assigning path names to strings and using the strings in initialization.

string s1 = "../data/book.txt";
string s2 = "../data/film.txt";
string s3 = "../data/video.txt";
string s4 = "../data/periodic.txt";
array<string, 4> path_names = {s1, s2, s3, s4};

And if you want to avoid copies here, you can use std::move:

array<string, 4> path_names = {std::move(s1), std::move(s2), std::move(s3), std::move(s4)};
P.W
  • 26,289
  • 6
  • 39
  • 76
  • Second variant doesn't look any better to me than the one in the question; at least, I'd move the strings instead of copying (`std::move(sN)`)... – Aconcagua Sep 17 '18 at 06:12
  • Updated the answer suggesting `std::move` as well. – P.W Sep 17 '18 at 11:19