5 ways to create an Array of String
- Using Pointers
- Using 2-D Array
- Using the String Class
- Using the Array Class
- Using the Vector Class
Conclusion: Out of all the methods, Vector seems to be the best way for creating an array of Strings in C++.
1. Using Pointers
#include <iostream>
const char* colors[4] = {"blue", "red", "green", "yellow"}; // const was added because string literals (literally, the quoted strings) exist in a read-only area of memory
for (int i = 0; i < 4; i++) { std::cout << colors[i] << std::endl;}
2. Using 2-D Array
#include <iostream>
char colors[][10] = {"blue", "red", "green", "yellow"}; // multidimensional array must have bounds for all dimensions except the first
for (int i = 0 ; i < 4; i++) { std::cout << colors[i] << std::endl;}
3. Using the String Class
The strings are also mutable.
#include <iostream>
#include <string>
std::string colors[] = {"blue", "red", "green", "yellow"};
for (int i = 0 ; i < 4; i++) { std::cout << colors[i] << std::endl;}
4. Using the Array Class
An array is a homogeneous mixture of data that is stored continuously in the memory space. The STL container array can be used to allocate a fixed-size array. It may be used very similarly to a vector, but the size is always fixed.
#include <iostream>
#include <string>
#include <array>
std::array<std::string, 4> colors {"blue", "red", "green", "yellow"};
for (int i = 0; i < 4 ; i++) { std::cout << colors[i] << "\n";}
5. Using the Vector Class
Both the number of strings and string contents are mutable.
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> colors {"blue", "red", "green"};
colors.push_back("yellow");
for (int i = 0; i < colors.size() ; i++) { std::cout << colors[i] << "\n";}
标签:std,String,colors,Using,array,include,Class
From: https://www.cnblogs.com/shendaw/p/17104656.html