如何使用set方法向数组中添加颜色字符串



我正在尝试使用set方法将7种颜色应用于c++中的数组。我不完全确定如何在主函数中使用setElement方法来帮助我将颜色附加到数组中的索引,因为我在网上或书中找不到任何帮助。到目前为止,我已经:


#include <iostream>
#include <string>
using namespace std;
class randColor 
{
private:
string colors[7];
public: 
void setElement(index, "color")
{
colors[] = index; 
index = "color";
}
void printColor()
{
int i = 0;
for(i = 0; i <= 7; i++)
{
cout << colors[i] << endl;
}
}
};
int main()
{
randColor RandomOne;
RandomOne.setElement(index, {"red", "orange", "yellow", "blue", "green", "indigo", "violet"});
RandomOne.printColor();
return 0;
}

setElement()只用于设置一个元素,不能给它一个数组。

您需要声明函数参数的类型,它们不应该用引号括起来。

void setElement(unsigned int index, std::string color)
{
colors[index] = color;
}

如果你想设置所有的元素,你需要在一个循环中调用它。

std::string rainbow[] = {"red", "orange", "yellow", "blue", "green", "indigo", "violet"};
for (int i = 0; i < sizeof rainbow/sizeof *rainbow; i++) {
RandomOne.setElement(i, rainbow[i]);
}

您的setElement()方法实现完全错误。它需要看起来像这样:

void setElement(int index, const string &color)
{
colors[index] = color;
}

此外,您的printColor()方法超出了数组的范围。循环需要使用<而不是<=:

for(i = 0; i < 7; i++)

然后,你的main()应该是这样的:

int main()
{
randColor RandomOne;
RandomOne.setElement(0, "red");
RandomOne.setElement(1, "orange");
RandomOne.setElement(2, "yellow");
RandomOne.setElement(3, "blue");
RandomOne.setElement(4, "green");
RandomOne.setElement(5, "indigo");
RandomOne.setElement(6, "violet");
RandomOne.printColor();
return 0;
}

或者:

int main()
{
randColor RandomOne;
const string colors[] = {"red", "orange", "yellow", "blue", "green", "indigo", "violet"};
for(int i = 0; i < 7; ++i) {
RandomOne.setElement(i, colors[i]);
}
RandomOne.printColor();
return 0;
}

如果您想在main()函数中保持setElement()函数调用的原样,您可以使用std::initializer_list,尽管我个人不建议在这种情况下使用。

#include <iostream>
#include <string>
#include <initializer_list>
using namespace std;
class randColor
{
private:
string colors[7];
public:
void setElement(int index, initializer_list<string> cols)
{
int i = 0;
for (auto it = cols.begin(); ++it; it != cols.end()) {
if (i++ == index) {
colors[i] = *it;
break;
}
}
}
void printColor()
{
int i = 0;
for (i = 0; i < sizeof(colors) / sizeof(string); i++)
{
cout << colors[i] << endl;
}
}
};
int main()
{
randColor RandomOne;
int index = 5;
RandomOne.setElement(index, { "red", "orange", "yellow", "blue", "green", "indigo", "violet" });
RandomOne.printColor();
return 0;
}

最新更新