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"

3
  • 6
    Why didn't you declare a return type for races()? Commented Jun 19, 2019 at 1: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? Commented Jun 19, 2019 at 1: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. Commented Jun 19, 2019 at 16:00

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.