I would like to take the return value from the function on the top and then do something with it in the function on the bottom. What should I put in the bottom function to use the value that was returned from "loadVectorWithReturn"
I do realize that I could create a new variable and store it there for later recall but I am trying to do more complicated things now.
Thank you
double vectors1::loadVectorWithReturn() {
vectors1 v1;
for (int i = 0; i <= 10; i++) {
v1.value.push_back(i);
cout << v1.value[i] << ", ";
}
cout << endl;
cout << v1.value[5] << endl;
return v1.value[5];
}
double doSomethingWithVectorReturn(TAKE IN VALUE FROM loadVectorWithReturn) {
//do something with v1.value[5];
}
If you are saying, "I don't want to make a global variable for v1", you could do this.
double vectors1::loadVectorWithReturn() {
vectors1 v1;
for (int i = 0; i <= 10; i++) {
v1.value.push_back(i);
cout << v1.value[i] << ", ";
}
cout << endl;
cout << v1.value[5] << endl;
return v1.value[5];
}
double vectors1::doSomethingWithVectorReturn() {
int returned = loadVectorWithReturn();
//Do something with returned.
}
Note: the "vectors1::" in front of "doSomethingWithVectorReturn" allows "doSomethingWithVectorReturn" to use the "loadVectorWithReturn" function.
Keep in mind that if you are only using the "returned" value one time (or multiple although that can be slower in many cases), you could skip setting the variable and just use "loadVectorWithReturn()" in place of it.
Example (Simply cout's the value):
double vectors1::doSomethingWithVectorReturn() {
cout << loadVectorWithReturn();
}
I am feeling like you are needing this because you will use loadVectorWithReturnlater within doSomethingWithVectorReturn in some point.
If this is the situation we can use:
#include <iostream>
#include <functional>
struct A
{
int fooA() const
{
return 5;
}
};
void doSomethingWithA( std::function<int()> foo )
{
std::cout << foo();
}
int main()
{
A a;
doSomethingWithA([a]()
{
return a.fooA();
});
}
Related
I am a beginner in programming.I have a problem. I am trying to code the Enigma machine. I have two classes. One for Enigma, one for rotors. Rotors are small parts of the enigma machine, that doesn't matter for the problem. My problem is the error. I cannot cout, the function cout << rotors[0].GetRotor(); which should return my vector of integers. I have no idea why is that. I don't need that to my program, but I'm not sure if my adding rotor to enigma void AddRotor(Rotor rotor) { rotors.push_back(rotor); }function, called in "TakeRotors" function, works right. In my opinion, it should work well, but I can't check it. Debugger, unfortunately, doesn't show any values of vector<Rotor> rotors; permutation so I am not sure :( Any help would be great. Thank You.
Here's my full, needed code :)
#include <iostream>
#include <vector>
using namespace std;
class Rotor {
public:
vector <int> permutation;
int position;
Rotor(vector<int> permutation) {
position = 0;
permutation;
}
vector<int> GetRotor() const {
return permutation;
}
};
class Enigma {
public:
vector<Rotor> rotors;
void AddRotor(Rotor rotor) {
rotors.push_back(rotor);
}
void PrintRotor(const vector<Rotor>& rotors) {
cout << rotors[0].GetRotor(); // Error right here
cout << rotors[0].position;
}
void setupRotor(int index) {
Rotor rotor = rotors[index];
}
void MoveRotor(int index) {
rotors[index].position++;
cout << "Before" << endl;
// cout << rotors[index].permutation.data << ' ';
Enigma::PrintRotor(rotors);
rotate(rotors[index].permutation.begin(), rotors[index].permutation.begin() + rotors[index].permutation.size(), rotors[index].permutation.end());
cout << "After" << endl;
Enigma::PrintRotor(rotors);
}
};
vector<int> take_numbers(int number) {
vector<int> numbers;
for (int i = 0; i < number; i++) {
int number;
cin >> number;
numbers.push_back(number);
}
return numbers;
}
void take_rotors(int number_letters, Enigma* enigma) {
int numberOfRotors;
// int numberOfNotch, positionOfNotch;
cout << "Give number of Rotors" << endl;
cin >> numberOfRotors;
for (int i=0; i < numberOfRotors; i++) {
vector<int> permutation = take_numbers(number_letters);
Rotor Rotor(permutation);
enigma->AddRotor(Rotor); // I am not sure if it adds Rotors fine.
}
}
int main()
{
Enigma enigma;
int number_letters, move_rotor;
cout << "Give number of letters in alphabet" << endl;
cin >> number_letters;
take_rotors(number_letters, &enigma);
// take_reflectors(number_letters, &enigma);
cout << "Which rotor do you want to move (index)" << endl;
cin >> move_rotor;
enigma.MoveRotor(move_rotor);
return 0;
}
There is no operator<<(std::ostream&,const std::vector<int>&) if you want it you need to supply your own. However, overloading operators for types you don't own is not recommended, so I would rather write a function:
void print_vector(std::ostream& out, const std::vector<int>& vect) {
for (int i : vect) {
out << i << '\n';
}
}
That you can call like this
print_vector(std::cout, rotors[0].GetRotor());
Alternatively you can supply an overload for << that prints all the Rotor:
std::ostream& operator<<(std::ostream&,const Rotor& rotor) {
out << rotor.position;
for (auto& i : rotor.GetRotor()) {
out << i;
}
// modify and add more to your likings
return out;
}
Once you have that you can also provide an overload to print a vector of rotors that you can use in Enigma::PrintRotor (which currently only prints the first element of the vector):
std::ostream& operator<<(std::ostream& out,const std::vector<Rotor>& rotors) {
for (const auto& r : rotors) {
out << r << '\n';
}
return out;
}
PS your naming is a little confusing. A Rotor has a GetRotor which returns permutations !?! I strongly suggest to use better names. If I have Rotor r; then r is the Rotor and it is not obvious what a GetRotor will do. Maybe rename it to GetPermutations?
In this example, the compiler says the function "list" doesn't have a definition, despite me writing one below. If I move the function definition to the top so there is no prototype, it compiles fine.
Can someone explain what's happening here?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void stuff();
void list(vector<string> things);
bool alive = true;
int main()
{
vector<string> things;
things.push_back("Lots");
things.push_back("Of");
things.push_back("Things");
do
{
cout << "What do you want to do?\n\n" << endl;
string input;
cin >> input;
if (input == "stuff")
{
stuff();
}
if (input == "list")
{
list();
}
} while (alive);
return 0;
}
void list()
{
cout << "The things are:\n\n";
for (int i = 0; i < things.size(); ++i)
{
cout << things[i] << endl;
}
}
void stuff()
{
cout << "Some stuff" << endl;
}
Your list function definition signature differs from your function declaration. The function signature should be the same. Your function definition signature should also accept one parameter:
void list(std::vector<string> things)
{
std::cout << "The things are:\n\n";
for (int i = 0; i < things.size(); ++i)
{
std::cout << things[i] << '\n';
}
}
And in your program you call the function with:
list();
where it should be:
list(things);
void list(vector<string> things); is not the same as void list(). You need to actually define your function as void list(vector<string> things) not just the prototype.
I have the following example (simplified) using a struct:
#include <iostream>
#include <algorithm>
#include <time.h>
using namespace std;
struct s_str
{
int a=1,b=2,c=3;
};
int main(void)
{
s_str str;
int sel;
srand(time(NULL)); //initialize random seed
sel = rand() % (3); //generate a random number between 0 and 2
cout << "sel: " << sel << endl;
cout << "str: " << str.??? << endl;//I was wondering to output a, b or c
return 0; //depending whether sel=0,1,2respectively.
}
When the struct "str" is defined, we can access to each element by using the opertor "." followed by the name of the element. For instance "str.c" will give us the number 3.
However in this example we don't know the element of "str" to output when programing because it's randomly selected by sel.
I don't know how to output "str.???" from sel number, that is, str.a if sel=0, str.b if sel=1, and str.c if sel=3.
I tried something like "str.[sel]", but it didn't work. Can you help me?
PD: I don't want to bother too much, but how to solve the same problem but now supposing that a,b and c have different variable type. For example:
int a=1,b=2;
string c="hola";
I tried to do it with two operators, but it didn't compile because they were overloaded.
As mentioned you can't do this without providing a certain mapping and indexing operator. The following should work well:
struct s_str
{
int a=1,b=2,c=3;
int& operator[](int index) {
switch(index) {
case 0:
return a;
case 1:
return b;
case 2:
return c;
default:
throw std::out_of_range("s_str: Index out of range.");
break;
}
}
};
int main() {
s_str s;
cout << s[0] << ", " << s[1] << ", " << s[2] << endl;
// cout << s[42] << endl; // Uncomment to see it fail.
return 0;
}
In general, no.
If the only distinguishing feature of the elements of the struct is their index, define a vector or array in the struct.
If you sometimes want to refer to the elements by name and sometimes by position, define an operator []( int ) for the struct.
Te easiest way, if you have only a couple of ints in your structure is:
struct s_str
{
int a = 1, b = 2, c = 3;
int& operator[] (size_t t) {
assert(t<3); // assumption for the following to return a meaningful value
return (t == 0 ? a : (t == 1 ? b : c));
}
};
You'd access with
cout << "str: " << str[sel] << endl;
and you could even use int to assign, because it's by reference:
str[sel] = 9;
cout << "a,b,c=" << str.a << "," << str.b << "," << str.c << endl;
I have a Spieler class and a Verein class with a vector of Spieler members.
Now if I change something of the Players like the Staerke(german for strength) by using a function of this class in the player class it does not automatically change the value for this player.
Here is the code:
#include <vector>
#include<iostream>
#include <string>
using namespace std;
class Spieler
{
public:
void setinformation(int a, string b, string c, int d)
{
ID = a;
Vorname = b;
Nachname = c;
Staerke = d;
}
void getinformation()
{
cout << "ID: " << ID << endl;
cout << "Vorname: " << Vorname << endl;
cout << "Nachname: " << Nachname << endl;
cout << "Staerke: " << Staerke << endl << endl;
}
void setStaerke(int x)
{
Staerke = x;
}
int getStaerke()
{
return Staerke;
}
private:
string Vorname, Nachname;
int Staerke, ID;
};
class Verein
{
public:
void setSpielerListe(vector<Spieler> x)
{
Spielerliste = x;
}
vector<Spieler> getSpielerListe()
{
return Spielerliste;
}
string getVereinsName()
{
return VereinsName;
}
int getVereinsID() const
{
return VereinsID;
}
void setVereinsID(int x)
{
VereinsID = x;
}
int getGesamtstaerke()
{
Gesamtstaerke = 0;
vector<Spieler> b;
b = getSpielerListe();
for (size_t i = 0; i < b.size(); i++)
{
Gesamtstaerke = Gesamtstaerke + b[i].getStaerke();
}
return Gesamtstaerke;
}
void Vereinsinformationen()
{
vector<Spieler> list;
int id;
string vereinsname;
int gesamtstaerke;
id = getVereinsID();
vereinsname = getVereinsName();
gesamtstaerke = getGesamtstaerke();
list = getSpielerListe();
cout << "VereinsID: " << id << endl;
cout << "Vereinsname: " << vereinsname << endl;
cout << "Gesamstaerke: " << gesamtstaerke << endl << endl;
cout << "Spieler: " << endl;
for (size_t i = 0; i < list.size(); i++)
list[i].getinformation();
}
private:
vector<Spieler> Spielerliste;
int VereinsID, Gesamtstaerke;
string VereinsName;
};
vector<Spieler> spieler;
int main()
{
Spieler Spieler1;
Spieler1.setinformation(0, "Peter", "Pan", 10);
spieler.emplace_back(Spieler1);
Verein Team1;
Team1.setSpielerListe(spieler);
Spieler1.setStaerke(20);
Team1.Vereinsinformationen();
cin.get();
return 0;
}
I'm really new into c++ and programming so the code might be terrible.
Guess it has to do with pointers, I'm really not into the concept of storing data in c++, try to get it by trial & error; So how to change the Staerke in a way that it is changed in the Teams Playerlist too?
The problem is you are storing full object in the vector and not pointers. When you run this line:
spieler.emplace_back(Spieler1);
a copy of Spieler1 is made and put in the vector. So modifying it in the main will have no effect in the vector. Also not that you are copying the vector when setting in Verein class.
You should use pointer if this is what you are after or better yet have a function to modify strength from Verein class taking its id and new strength as parameters might be a good idea. Something like this:
void setStaerke(int id, int x)
{
vector<Spieler>::iterator it = Spielerliste.begin();
while (it != Spielerliste.end())
{
if ((*it).GetId() == id)
{
(*it).setStaerke(x);
break;
}
}
}
If you have access to C++11, it could be made more elegantly.
Hereby you pass and store a copy from the vector into the object:
Team1.setSpielerListe(spieler);
Therefore changes to the original vector and the contained objects will not affect the member.
Further, I don't have much experience with emplace_back, but the more usual way to append an object to a std::vector would also append a copy:
spieler.push_back(Spieler1);
Therefore changes to the original object would not affect the object you've appended to the container.
Make sure you better understand when objects are copied.
For reference:
http://en.cppreference.com/w/cpp/container/vector/emplace_back
http://en.cppreference.com/w/cpp/container/vector/push_back
How to pass objects to functions in C++?
I have the following code in a class member function:
int state = 0;
int code = static_cast<int>(letter_[i]);
if (isalnum(code)) {
state = testTable[state][0];
} else if (isspace(code)) {
state = testTable[state][2];
} else if (code == OPEN_TAG) {
state = testTable[state][3];
} else if (code == CLOSE_TAG) {
state = testTable[state][4];
} else {
state = testTable[state][1];
}
switch (state) {
case 1: // alphanumeric symbol was read
buffer[j] = letter_[i];
++j;
break;
case 2: // delimeter was read
j = 0;
// buffer.clear();
break;
}
However, if state is a class member variable rather than local, the performance drops considerably (~ 5 times). I was reading about differences in accessing local variables and class members, but texts usually say that it affects performance very slightly.
If it helps: I am using MinGW GCC compiler with -O3 option.
I could not reproduce your observation, testing on x86_64 with both, VS10 and g++. The local variant is slightly faster, probably due to what Alan Stokes described in his comment, but at most ~10%. You should check your timing, try to rule out any other problems and best would be the reduce all your code to a very simple test-cast which still shows this behavior.
I think my test-case resembles your scenario quite good, at least like you described it:
#include <iostream>
#include <boost/timer.hpp>
const int max_iter = 1<<31;
const int start_value = 65535;
struct UseMember
{
int member;
void foo()
{
for(int i=0; i<max_iter; ++i)
{
if(member%2)
member = 3*member+1;
else
member = member>>1;
}
std::cout << "Value=" << member << std::endl;
}
};
struct UseLocal
{
void foo()
{
int local = start_value;
for(int i=0; i<max_iter; ++i)
{
if((local%2)!=0) /* odd */
local = 3*local+1;
else /* even */
local = local>>1;
}
std::cout << "Value=" << local << std::endl;
}
};
int main(int argc, char* argv[])
{
/* First, test using member */
std::cout << "** Member Access" << std::endl;
{
UseMember bar;
bar.member = start_value;
boost::timer T;
bar.foo();
double e = T.elapsed();
std::cout << "Time taken: " << e << "s" << std::endl;
}
/* Then, test using local */
std::cout << "** Local Access" << std::endl;
{
UseLocal bar;
boost::timer T;
bar.foo();
double e = T.elapsed();
std::cout << "Time taken: " << e << "s" << std::endl;
}
return 0;
}