2

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?

6
  • Did you try to use string literals instead of numbers in the initializer? Commented Sep 17, 2018 at 5:12
  • It didn't occur to me that would work. I'll try that. Commented Sep 17, 2018 at 5:13
  • Possible duplicate of Using std::array with initialization lists Commented Sep 17, 2018 at 5:52
  • at does range checking - obsolete if you are sure that indices are in range (which applies in given case), so prefer index operator []... Commented Sep 17, 2018 at 6:00
  • 1
    @Galaxy Yes and yes... Commented Sep 19, 2018 at 5:35

1 Answer 1

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)};
Sign up to request clarification or add additional context in comments.

2 Comments

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))...
Updated the answer suggesting std::move as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.