Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/154.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将一组字符串分配给向量c++;_C++_Vector - Fatal编程技术网

C++ 将一组字符串分配给向量c++;

C++ 将一组字符串分配给向量c++;,c++,vector,C++,Vector,我有一个名为months的向量,它反复包含数字1-12。这些数字是从文件中读取的。我怎样才能在这个特定的向量中使用数字1=“一月”,2=“二月”,3=“三月”等,这样在使用cout时,使用一个固定的月份名称数组并在必要时访问这些名称对我来说更有意义。months中存储的索引范围为1到12,因此我们需要从索引中减去1以访问正确的月份: std::string month_names[] = { "January", "February", // ... }; // ...

我有一个名为
months
的向量,它反复包含数字1-12。这些数字是从文件中读取的。我怎样才能在这个特定的向量中使用数字1=“一月”,2=“二月”,3=“三月”等,这样在使用cout时,使用一个固定的月份名称数组并在必要时访问这些名称对我来说更有意义。
months
中存储的索引范围为1到12,因此我们需要从索引中减去1以访问正确的月份:

std::string month_names[] = {
    "January",
    "February",
    // ...
};

// ... Get the month indices from a file ...

std::cout << month_names[months[3] - 1] << std::endl;
std::字符串月份名称[]={
“一月”,
“二月”,
// ...
};
// ... 从文件中获取月份索引。。。

std::cout定义一个带有月份名称的字符串文本数组,并使用向量元素作为该数组的索引就足够了。比如说

const char *month_name[] = 
{ 
    "January", "February", "March", /*...*/ "December" 
};

std::cout << month_name[ months[i] - 1] << std::endl;
const char*month_name[]=
{ 
“一月”、“二月”、“三月”、“十二月”
};

std::cout您可以使用
std::map
将数字与字符串相关联

#include <map>
#include <string>
#include <iostream>

using namespace std;

int main()
{
   std::map<int, std::string> Month = {{1,"January"}, {2,"February"}, {3,"March"} /* etc */ };
   cout << Month[3] << endl;
}

实时示例:

存储字符串而不是整数?或者情况比您描述的还要复杂?我正在将文件中的数字读入整数,但使用cout时,我希望显示月份的实际名称,而不是数字@MikeSeymourse使用int和string组合对映射进行着色。听起来您仍然只需要字符串向量。如果在数组中添加一个伪值作为第一项,则不必从索引中减去1。:-)内存或速度优化这一由来已久的问题。在本例中,这可能无关紧要。哇,您没有使用虚拟值作为第一个条目。虚拟值删除了从索引中减去1的要求。
#include <map>
#include <string>
#include <iostream>

using namespace std;

int main()
{
   std::map<int, std::string> Month = {{1,"January"}, {2,"February"}, {3,"March"} /* etc */ };
   cout << Month[3] << endl;
}
March