0

I want to make a simple function that takes an int as input, makes a vector filled with string elements, then returns a string corresponding to the index of the element.

Everything seems to be fine with the code, no red squiggly lines or anything, but when I compile nothing happens at all.

I've used the push_back() method to fill the vector, so that isn't the problem.

#include <iostream>
#include <vector>
#include <string>

races(int a) {
    std::vector<std::string> race = { "Human", "Cyborg", "Android", "Aster","Ool-Rog","Criataz" };
    return race[a];
};

I've run it on a browser coding site and nothing happens, and when I code it in Visual Studio I get an error:

"cannot find class to resolve delegate string"

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 6
    Why didn't you declare a return type for `races()`? – genpfault Jun 19 '19 at 01:05
  • 4
    To elaborate on what genpfault said, `races()` needs to be declared as `std::string races(int a)`. But more importantly, where is your `main()` that actually calls `races()` at runtime? – Remy Lebeau Jun 19 '19 at 01:06
  • 1
    the int main is missing because i just copied the function giving me trouble sorry ill be sure to include the full code next time. As the std::string races() was actually missing so thank you for your help guys. I am very new at programming. – hostboy221 Jun 19 '19 at 16:00

1 Answers1

3

as per comments by genpfault and Remy Lebeau, here is a working code sample:

#include <iostream>
#include <vector>
#include <string>

std::string races(int a) {
    std::vector<std::string> race = { "Human", "Cyborg", "Android", "Aster","Ool-Rog","Criataz" };
    return race[a]; // or race.at(a);
};

int main () {
    std::cout << "Race with index: " << 2 << " is: " << races(2) << std::endl;
    return 0;
}

Example compilation and execution, with results on MAC OSX with C++ 14 installed, in Terminal utilities app:

$ /usr/local/bin/c++-9 races.cpp -o races
$ ./races
Race with index: 2 is: Android

Keep on coding!

  • 6
    The OP is (correctly) avoiding the use of `using namespace std;`; please don't encourage bad habits by adding it to their code for minimal benefit. See [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/364696) – ShadowRanger Jun 19 '19 at 01:50