This question already has answers here:
Code outside functions
(3 answers)
Closed 2 years ago.
#include <iostream>
using namespace std;
int *i = new int;
*i = 0;
int &j = *i;
j++;
//cout << *i << endl;
I have a code like that, and I know this syntax is true but it gives warning in Visual Studio Code like this:
quiz2_q8.cpp:5:4: error: expected constructor, destructor, or type conversion before '=' token
*i = 0;
^
quiz2_q8.cpp:7:1: error: 'j' does not name a type
j++;
Am I missing a library to include? I thought iostream is enough for this quiz code.
You can't have arbitrary statements in the global namespace. You need to put it into a function, e.g. like this:
int main() {
int *i = new int;
*i = 0;
int &j = *i;
j++;
}
Most programs have a starting point, which is the main method/function/procedure whatever you want to call it. Each function has a scope given by { // fun scope }. A good tutorial series on C++ might come to your aid, or perhaps a book. With that said here's a template for such a program.
#include <iostream>
using namespace std;
int main(){
return 0;
}
Statements for being executed must be inside functions.
#include <iostream>
using namespace std;
int main(void) { // add this
int *i = new int;
*i = 0;
int &j = *i;
j++;
//cout << *i << endl;
} // add this
Related
I have just started learning parallel programming in c++ and wanted to use HPX for it. I need to complete several tasks in groups of N and I wanted to write code that puts all the threads into a vector and when at least one is done replace it with the next thread.
#include <iostream>
#include <vector>
#include "hpx/hpx_main.hpp"
#include "hpx/future.hpp"
using namespace std;
int dummy(int a){
return a;
}
int main(){
vector<hpx::future<int>>futures;
futures.reserve(3);
for(int step = 0; step < 3; step++){
futures.push_back(hpx::async(dummy, step));
}
int index;
auto f2 = hpx::when_any(futures).then([&](auto f){
return f;
});
auto res = f2.get();
vector<hpx::future<int>> fut3 = res.futures;
for(int i = 0; i < fut3.size(); i++){
cout << fut3[i].get() << endl;
}
}
This code results in a following error:
error: static assertion failed: result type must be constructible from input type
I have tryied to find solutions online, but there is barely any examples of code with hpx.
Try adding std::move when copying the resulting futures:
std::vector<hpx::future<int>> fut3 = std::move(res.futures);
The problem is that res.futures is invalidaded after the copy.
So here's my code at the moment:
#include <iostream>
using namespace std;
int main() {
string x = "_one";
int sound_one = 7;
int sound_two = 8;
cout << ("sound") + x;
}
However when I run the code, it outputs 'sound_one' instead of '7'. How do I get it to output the variable sound_one instead of just 'sound_one'? Also, I need it so I can change x to different things (eg '_two') so it will then output sound_two instead. Any help would be greatly appreciated.
C++ is not a reflective language in the sense that you can acquire a variable name at runtime (variable names are normally compiled out of the program). You can use std::map though to achieve your immediate aim:
#include <iostream>
#include <string>
#include <map>
int main() {
using std::literals::string_literals::operator""s;
std::string x = "_one";
std::map<std::string, int> data;
data["sound_one"] = 7;
data["sound_two"] = 8;
std::cout << data["sound"s + x];
}
Note the notation "sound"s: the suffixed s denotes a std::string user defined literal.
You can't a variable from a string in this way. A work around is to use if/switch statements until the variable name is matched and then print it:
if(x == "_one") {
cout << sound_one;
}
else if(x == "_two") {
cout << sound_two;
}
else {
cout << "no match";
}
You can't do that in C++. You can use a map as shown in another answer, but I feel like what you really need is an array:
#include <format>
#include <iostream>
int main()
{
int data[] { 7, 8 };
std::cout << std::format("data[{}] = {}\n", 0, data[0]);
}
Arrays are usually better for such simple ordered sequences.
This question already has answers here:
Compilation Error: void value not ignored as it ought to be in std::queue::pop() [duplicate]
(2 answers)
Invalid use of void expression with a Queue and .pop()
(2 answers)
Why doesn't std::queue::pop return value.?
(6 answers)
Closed 2 years ago.
Coding in C+, using Visual Studio 2019, I have a structure defined. I am creating a queue of that data structure and have pushed 2 elements into the queue. Now the question is how to access the members of the structure elements inside the queue?? Any guidance is appreciated!
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <queue>
typedef struct _myqueuestruct
{
string name;
int citypin;
int employeeId;
}myqueuestruct;
int main()
{
queue<myqueuestruct> myQ;
myqueuestruct myQelement;
myQelement.name = "Harry";
myQelement.citypin = "Ohio";
myQelement.employeeId = "345";
// Insert some elements into the queue
myQ.push(myQelement);
myQelement.name = "John";
myQelement.citypin = "Jaipur";
myQelement.employeeId = "223";
// Insert some elements into the queue
myQ.push(evtSvcElement);
//myQ.size();
//queue<myqueuestruct>::iterator it = myQ.begin();
for (int i = 0; i < myQ.size(); i++)
{
cout << myQ.front();
myQ.pop(); //???? How do I access the member values of the elements of the queue?
}
while (1);
return 0;
}
Well, front returns a reference to the first element, so like this:
std::cout << myQ.front().name; // and similarly for other elements
Or, for example, make a referenence yourself:
auto& ref = myQ.front();
ref.name = "foo";
ref.citypin = 42;
// etc.
I have modified your code to get it compiling and working: (Note: I have used C++17 standard using g++ to compile this code but it should work for visual studio 2019
#include <iostream>
#include <queue>
typedef struct _myqueuestruct
{
std::string name;
std::string citypin;
int employeeId;
}myqueuestruct;
int main()
{
std::queue<myqueuestruct> myQ;
myqueuestruct myQelement;
myQelement.name = "Harry";
myQelement.citypin = "Ohio";
myQelement.employeeId = 345;
// Insert some elements into the queue
myQ.push(myQelement);
myQelement.name = "John";
myQelement.citypin = "Jaipur";
myQelement.employeeId = 223;
// Insert some elements into the queue
myQ.push(myQelement);
while (myQ.size() > 0)
{
auto & e = myQ.front();
std::cout << "Name: " << e.name
<< " CityPin: " << e.citypin
<< " EmployeeId: " << e.employeeId << std::endl;
myQ.pop();
}
return 0;
}
I would like to point out a few changes I have to make in your above code:
in your struct definition you used int datatype but you assigned char string to the same. I have modified the datatype to be std::string.
using while loop for iterating through all the elements and using myQ.size() every time instead of using for loop.
std::cout - holding the element reference in a local variable inside the loop and printing all member variables.
Improvements you can make to above code:
There are multiple transient copies of the object being created when you push the object into the queue. I would suggest refer std::queue documentation here: http://www.cplusplus.com/reference/queue/queue/ and try to enhance above code with
emplace_back
overload operator<< for your class for printing class members, this would help you learn about operator overloading.
This question already has answers here:
Undefined behavior and sequence points
(5 answers)
Closed 2 years ago.
I was trying to calculate a factorial using recursion like this:
#include <iostream>
using namespace std;
int factorial(int a)
{
if(a == 0)
{
return 1;
}
return a*factorial(--a);
}
int main()
{
int a;
cin >> a;
cout << factorial(a) << endl;
return 0;
}
and it wasn't working. Then, I made a small change:
#include <iostream>
using namespace std;
int factorial(int a)
{
if(a == 0)
{
return 1;
}
return a*factorial(a-1);
}
int main()
{
int a;
cin >> a;
cout << factorial(a) << endl;
return 0;
}
... and it started working!
The problem is that I don't see any difference between these codes: Why didn't it work in the first code?
In your first code sample, the following line has undefined behaviour:
return a * factorial(--a);
This is because there is nothing in the C++ Standard that dictates whether or not the 'old' or 'new' (decremented) value of a is used to multiply the return value of the factorial function.
Compiling with clang-cl gives the following:
warning : unsequenced modification and access to 'a' [-Wunsequenced]
In your second code sample, there is no such ambiguity, as a is not modified.
I am trying to create a simple stack using vector in C++.
Here is the code:
#include <vector>
class Site
{
public:
int i; // site position i (x-axis)
int s; // site state
vector<Site> neighbors;
Site(void);
Site(int ii, int ss);
void AddNeighbor(Site &site);
};
Site::Site()
{
i = -1;
s = -1;
vector<Site> neighbors;
}
Site::Site(int ii, int ss)
{
i = ii;
s = ss;
}
void Site::AddNeighbor(Site &site)
{
neighbors.push_back(site);
}
void testStack()
{
int tot = 600;
vector<Site> myStack();
int i = 0;
while (i < tot)
{
Site site(i, 1);
myStack.push_back(site);
i++;
}
i = 0;
while (i < tot)
{
Site *site = myStack.back();
myStack.pop_back();
cout << site->i << site->s << endl;
i++;
}
}
Compiler errors:
ising_wolff.cpp: In function ‘void testStack()’:
ising_wolff.cpp:373:17: error: request for member ‘push_back’ in
‘myStack’, which is of non-class type ‘std::vector()’
myStack.push_back(site);
^ ising_wolff.cpp:380:30: error: request for member ‘back’ in ‘myStack’, which is of non-class type ‘std::vector()’
Site *site = myStack.back();
^ ising_wolff.cpp:381:17: error: request for member ‘pop_back’ in ‘myStack’, which is of non-class type
‘std::vector()’
myStack.pop_back();
What do these errors mean?
Here are some sites I have looked at:
1) Creating objects while adding them into vectors
2) push_back causing errors in C
3) how to create vectors of class object
How to create a vector of class objects in C++?
Start with something simpler so you can get the hang of it.
First, create a vector of primitive ints:
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> sites(5);
sites.push_back(5);
for(int x = 0; x < sites.size(); x++){
cout << sites[x];
}
cout << endl;
return 0;
}
Compiling it:
g++ -o test test.cpp
Running it:
./test
000005
Create a vector of class objects in a similar way as above:
#include <iostream>
#include <vector>
using namespace std;
class Site {
public:
int i;
};
int main() {
vector<Site> listofsites;
Site *s1 = new Site;
s1->i = 7;
Site *s2 = new Site;
s2->i = 9;
listofsites.push_back(*s1);
listofsites.push_back(*s2);
vector<Site>::iterator it;
for (it = listofsites.begin(); it != listofsites.end(); ++it) {
cout << it->i;
}
return 0;
}
Which should print:
79
vector<Site> myStack();
This is actually a function declaration. The function is called myStack and it returns a vector<Site>. What you actually want is:
vector<Site> myStack;
The type of neighbours at the moment will store copies of the objects, not references. If you really want to store references, I recommend using a std::reference_wrapper (rather than using pointers):
vector<reference_wrapper<Site>> neighbors;
vector<Site> myStack();
This is wrong. Lose the ().
You're declaring a function, not a vector.
Just write:
vector<Site> myStack;
You could use:
vector<Site> myStack;
myStack.resize(100); //will create 100 <Site> objects