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

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.

Related

c++ weird scope in if statement [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 1 year ago.
Improve this question
When I declare anything inside an if statement it doesn't propagate out of it, moreover, if I have a variable outside, and i redeclare it inside if statements it lost it once the code ends the statement, how can I manage to globalize the scope of an if statement.
Redeclaring a variable in an inner scope creates a new variable.
#include <iostream>
int main()
{
int i = 1;
if (true)
{
int i = 42; // variable is re-declared
} // lifetime of inner i ends here
std::cout << i; // expected output 1
}
You can reference a variable in an inner scope that was declared outside without re-declaring it.
#include <iostream>
int main()
{
int i = 1;
if (true)
{
i = 42; // variable from outer scope is used
}
std::cout << i; // expected output 42
}

String in 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 1 year ago.
Improve this question
I was working on a project and I've had a question: when I call a class that contain a string str, does the code create a string every time or it use the string I've already created?
For example:
#include <iostream>
using namespace std;
class exClass {
public:
void exVoid ( string valueStr )
{
str = "Hi";
cout << str;
}
private:
string str;
};
int main()
{
exClass myClass;
string stringMain;
while (1)
{
cout << "Insert value of str: ";
cin >> stringMain;
myClass.exVoid(stringMain);
}
}
so the question is: every time I call exClass, the class create the string str or it do that only once (when I call it for the first time)?
Following the flow of the program:
First you create an instance of exClass named myClass. This happens once.
Then you create a string named stringMain. This also happens once.
After that, you have an endless loop while(1). Inside this loop you:
Print on the output
Get input
Call function exVoid()
So, you create one instance of class exClass with one member str and use the same str (through your function) endlessly inside your loop.
Something to think about is the function argument. You never really use it. For it to have meaning in you code, you can do something like:
void exVoid ( string valueStr )
{
str = valueStr;
cout << str;
}
Yes, you're creating a copy of your input string every time you call exVoid. You can make it more efficient if you use a reference:
void exVoid(const std::string &value) {
...
}
The way you're calling it from main, you're thus passing a reference to stringMain, but by making it const, you know your method won't mess with it.

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.

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

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.

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;
}