How to initialize an Int from a map Value, C++ [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a large global map in a header of weapon names and ID numbers from a video game . I am trying to find a way that I can take user input for the name and return the item number. For this I created a new int and would like to initialize it with the map value after searching for the name. What is the best way to do this?
//header
#include <map>
#include <string>
using namespace std;
typedef std:: map <std :: string, int> weaponMap;
inline
weaponMap & globalMap() {
static weaponMap theMap;
static bool firstTime = true;
if (firstTime) {
firstTime = false;
theMap["weaponOne"] = 854000;
}
}
//Source.cpp
#includes "globalMap"
int swapWeapon = weaponMap::["weaponOne"];
cout << swapWeapon;

Well, there are multiple misconceptions you seem to have in your code:
//header
#include <map>
#include <string>
using namespace std;
typedef std:: map <std :: string, int> weaponMap;
inline
weaponMap & globalMap() {
static weaponMap theMap;
static bool firstTime = true;
if (firstTime) {
firstTime = false;
theMap["weaponOne"] = 854000;
}
return theMap; // this is necessary if you specify a return type
}
//Source.cpp
// #includes "globalMap" You have a typo here, that should be as follows
#include "globalMap"
// You cannot access the local static variable from the function in your code directly
// int swapWeapon = weaponMap::["weaponOne"];
int swapWeapon = globalMap()["weaponOne"]; // Note that this would initialize
// swapWeapon with 0 if "weaponOne"
// wasn't registered as a key
// You cannot use these statements outside of a function scope
// cout << swapWeapon;
int main() {
cout << swapWeapon;
}
See a live demo.
For this I created a new int and would like to initialize it with the map value after searching for the name.
In that case you need to move the initialization out from the global context:
int main() {
std::string weaponType;
std::cout "Input a weapon type: "
std::cin >> weaponType;
int swapWeapon = globalMap()[weaponType];
std::cout << swapWeapon;
}
More points
Do not use using namespace std; in header files (see here why)
In general avoid to have such flat Singleton Patterns, rather use a Abstract Factory to make your code more flexible for future maintenance.

Related

Retrieve element from list of Object in cpp [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I want to retrieve each element from the list of object in cpp and we have classes like below:
class User{
public:
bool isAvailable;
string value;
};
class Users{
public:
User dateFrom;
User dateTo;
User add1;
User add2;
};
Now somewhere else I have created a list of objects of User like std:: list<User> user-list, stored data and then pushback to the list of the object now I want to get that particular data like dateFrom,dateTo, etc.
user-list.push_back(dateFrom);
user-list.push_back(dateTo);
Now I want to access the element of user-list like what we access in list l1 by index like.
This is just a guess of what you might want:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class User {
public:
bool isAvailable;
string value;
};
int main()
{
User someuser;
someuser.value = "Some user";
someuser.isAvailable = true;
User someotheruser;
someotheruser.value = "Some other user";
someotheruser.isAvailable = true;
std::vector<User> user_list; // <<<< using std::vector here
user_list.push_back(someotheruser);
user_list.push_back(someuser);
cout << user_list[0].value << "\n";
cout << user_list[1].value << "\n";
}
We use a std::vector here instead of a std::list because you mention you wanted to access the elements of the list via an index.
Output is:
Some other user
Some user
Disclaimer: This code is still very poor, for example there are no constructors whatsoever.

Is it possible to set a custom return type for a class? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Is it possible to give a specific return type to a class?
For instance, I would like to make a class called Sentence, which is basically a vector of strings. Would it then be possible to define it so it has a return value of the vector of strings (assuming a vector/array can be a return value) ?
edit: I'm pretty tired right now so excuse my bad description. What I meant was setting it so that you could return the class, and it would return a specific variable inside the class. So I would essentially be making a Sentence class which was defacto a vector of strings as far as the compiler was concerned, just with some functions added in. That way if I told a function to return Sentence A it would return the vector of strings inside the object.
A class is a type. It is used to define objects; so it doesn't return anything.
However, you can define a conversion operator to convert easily an object of that type into another.
Example:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Sentence {
vector<string> words;
public:
Sentence() : words{} {} // construct an empty sentence
void add(string word) { // add a new word to the sentence
words.push_back(word);
}
operator vector<string> () { // convert into a vector of string
return words;
}
};
With such a conversion operator you can write code such as:
int main() {
Sentence statement; // create a sencence
statement.add("hello");
statement.add("word");
vector<string> w = statement; // convert the sentence into a vector
for (auto& x : w) cout <<x<<" "; // print the vector elements
cout <<endl;
return 0;
}
You could event have different conversion operators for different target types. For example, you could add this one to the class:
operator string() { // conversion to string
string r{};
for (auto x=words.begin(); x!=words.end(); r+=" ")
r += *x++;
return r;
}
You could then use it as follows:
string s = statement; // convert the Sentence into a string
cout<<s<<endl;
Online demo
Maybe you want conversion operator:
#include <iostream>
#include <string>
#include <vector>
#include <initializer_list>
class Sentence
{
private:
std::vector<std::string> words;
public:
Sentence(std::initializer_list<std::string> l) : words{ l } {}
operator std::vector<std::string>() // conversion operator
{
return words;
}
};
int main()
{
Sentence sentence {"hello", "world", "this", "is", "a", "test"};
std::vector<std::string> arr = sentence; //indicate that you want it to be treated as array
for (auto word : arr)
std::cout << word << std::endl;
return 0;
}
https://ideone.com/6pq3gE

Using built-in queue class of C++ to work within a class I create [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
For some reason, I can't seem to get the built-in queue class of C++ to work within a class I create in the way the same built-in queue works in main. I want the queue I use in my class to contain the values of the variables I add to it. But when I use the built-in queue in my class, the queue seems instead to contain something else, maybe addresses of the variables.
What am I doing wrong please?
#include <queue>
#include <iostream>
#include <cstdlib>
using namespace std;
class Myclass {
private:
queue<int> q;
public:
Myclass();
void qPush(int n){ q.push(n); }
int qFront(){ q.front(); }
void qPop(){ q.pop(); }
};
Myclass::Myclass() { // Default Constructor
}
int main () {
int num1 = 0;
int num2 = 1;
queue<int> myQ;
myQ.push(num1);
myQ.push(num2);
cout << myQ.front() << endl;
myQ.pop();
cout << myQ.front() << endl;
cout << "Myclass version: " <<endl;
Myclass b;
b.qPush(num1);
b.qPush(num2);
cout << b.qFront() << endl; // I want this to print out an int. But it looks like it may be printing out an address instead?
b.qPop();
cout << b.qFront() << endl;
return 0;
}
The output I get:
0
1
Myclass version:
537168208
537168212
The problem is that MyClass::qFront() doesn't have a return statement, and because of that it returns a garbage value.
You just need to add the return statement:
int qFront(){ return q.front(); }
To make this code work better you could also add const qualifier to make the method usable with const objects:
int qFront() const { return q.front(); }
Here is an example which demonstrates why it might be necessary:
Myclass a;
a.qPush(42);
const MyClass b = a;
cout << b.qFront(); // This line results in a error if the method isn't marked as const.
The rule here is that you should always mark methods that don't modify object state as const (if you don't have a good reason to do otherwise).
You could also add a second version (overload) of this function which would return a reference to int instead of actual int:
int qFront() const { return q.front(); }
int &qFront() { return q.front(); }
Then the first one would be used for const objects and the second one would be used for mutable ones.
Because it returns a reference to int instead of just a plain int, you could modify the returned value:
Myclass a;
a.qPush(42);
cout << a.qFront();
a.qFront() = 13;
cout << a.qFront();
(Note that compiler wouldn't allow you to write int &qFront() const { return q.front(); }, because it would allow you to modify contents of const objects, which is a bad thing.)

Initialializing a struct with predefined values [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
#include <iostream>
using namespace std;
int main()
{
struct naming
{
int numline;
string numname;
} naming = {{1,"ONE"},{2,"TWO"}};
cout<<naming.numline<<":"<<naming.numname<<std::endl;
return 0;
}
This error occurs:
main.cpp:10:33: error: braces around scalar initializer for type int
} naming = {{1,"ONE"},{2,"TWO"}};
You have
struct naming { … } naming = …
which means you're creating a single naming object. But your initializer
{{1,"ONE"},{2,"TWO"}}
doesn't match that intent.
Looks like you're trying to initialize a collection of naming objects. If that's the case you should make it a std::vector<naming> instead of a single object:
struct naming { … }; // definition of naming
std::vector<naming> namings = {{1, "ONE"}, {2, "TWO"}}; // collection of objects
Then you can access the individual naming objects like so:
// access the first element:
std::cout << namings.at(0).numline << ":" << namings.at(0).numname << std::endl;
// access the second element:
std::cout << namings.at(1).numline << ":" << namings.at(1).numname << std::endl;
Since you want to store two values , you will have to create an array of structure type.
#include <iostream>
using namespace std;
int main()
{
struct naming
{
int numline;
string numname;
} naming[] = {{1,"ONE"},{2,"TWO"}};
cout<<naming[0].numline<<":"<<naming[0].numname<<std::endl;
cout<<naming[1].numline<<":"<<naming[1].numname<<std::endl;
return 0;
}

C++: How can I used global variables in various different functions? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Is there some way I can have a global variable (in this case a vector) retain its contents throughout any functions? I'm trying to see if I can do this:
vector<string> collected_input; //global
void some_function{
string bla = "towel";
collected_input.push_back(bla); //collected_input gains "towel"
}
void some_otherfunction{
string xyz = "zyx"
collected_input.push_back(xyz); //collected_input gains "zyx"
}
int main(){
// print the contents of the collected_input vector
}
What you have shown will work just fine, provided main() is calling some_function() and some_otherfunction():
#include <ostream>
#include <vector>
#include <string>
using namespace std;
vector<string> collected_input;
void some_function()
{
string bla = "towel";
collected_input.push_back(bla);
}
void some_otherfunction()
{
string xyz = "zyx"
collected_input.push_back(xyz);
}
int main()
{
some_function();
some_otherfunction();
for (vector<string>::iterator iter = collected_input.begin();
iter != collected_input.end();
++iter)
{
cout << *iter << '\n';
}
return 0;
}
The code you posted will achieve what you are looking for. Your have a single instance of a vector (collected_input), which is used across multiple functions. Your vector is effectively global, and in fact it is possible for other source files to access it by declaring a vector of the same name using the extern keyword, although this is highly recommended against.
Of course, right now your program does nothing because your main() function does not contain any code. If you were to call both of your functions from main() and then print the vector, you will find that both functions successfully operated on the vector.