简体   繁体   中英

How to initialize an std::array of strings?

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 int s:

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 int s. How to do that?

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)};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM