if you want to output it:
for a console program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <vector> //std::vectors
#include <string> //std::strings
#include <cstdlib> //rand() function
#include <iostream> //std::cout and std::endl
int main()
{
std::vector<std::string> randoms;
std::vector<std::string> colors;
colors.push_back("red");
colors.push_back("blue");
colors.push_back("yellow");
colors.push_back("green");
colors.push_back("purple");
int however_many_random _colors_you_want=3; //example number
for(int i=0;i<however_many_random_colors_you_want;i++)
{
randoms.push_back(colors[rand() % 4]
// pick a random number 0-4 (because vectors start at 0 like chars)
// and send the color of the index (the random number) to the back of the randoms vector.
std::cout << randoms[i]; //output all the randoms at once.
std::cout << randoms[i] << " "; //output all the randoms with a space in between each
std::cout << randoms[i] << std::endl; //output all the randoms with a line break after each
//note: std::endl is pretty much the same as "\n"
}
std::cout << randoms[0] << std::endl << randoms[1] << std::endl; //output the first two randoms with a line break after each.
return 0;
}
|
what is the data type of
label1->Text
?
remember: both std::vector's were declared of the data type std::string. that means randoms[0] is a string and colors[0] is also a string. same with 1, 2, etc.
oh, just noticed this but randoms.push_back(the_string) adds the string to the end of the vector.
vectors are structured sorta like arrays....
myVector:
element0 | element1 | element2
if you do myVector.push_back(element3) myVector will be structured like this:
myVector:
element0 | element1 | element2 | element3
to undo vector.push_back(parameter) use vector.pop_back().
doing myVector.pop_back() (no parameters!) will return the structure to:
myVector:
element0 | element1 | element2
so
label1->Text=randoms.push_back();
will not work. try
label1->Text=randoms[0]
. this will store the first random number as label1->Text.
---
And just for future reference, if you ever need a vector-like-thing of multiple data types, #include <tuple> and use std::tuple. Like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
//using std::tuples in function form and variable form:
#include <tuple>
#include <string>
std::string err;
int number1 = 7;
int errno;
int main()
{
std::tuple<int, std::string> myFunction(int number)
{
if(number==1)
{
errno=0;
err="No error";
}
else
{
errno=1;
err="wrong number";
}
return std::make_tuple(errno, err);
}
std::tuple<int, std::string> result = myFunction(7);
return 0;
}
|