my code is shown here:
#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>
using std::string;
using std::endl;
using std::cout;
using std::cin;
struct funcs
{
std::vector<int> values;
int sum;
void createVectorValues(){
while(values.size() < 100)
{
int x = rand() % 100;
values.push_back(x);
}
for(int& a : values)
{
sum += 1;
}
cout << sum;
}
};
int main()
{
srand;
funcs myFunct;
myFunct.createVectorValues();
}
the following code results in a large value such as -858993360
How can I change this code so that it can function properly
You didn't define a constructor for funcs, so you get the default constructor, which invokes the default constructor of each member. This means the int member sum is left with an indeterminate value. See Does the default constructor initialize built-in types?. You probably want to write a constructor that initializes sum to 0.
srand; isn't a function call. It's valid syntax, because srand evaluates to a pointer to the srand function, but it's an expression with no side effects, so it does nothing. Much as if you had written 3;. To call the function, you need srand(arg), where arg is an appropriate integer. Or, switch to the C++11 random number generation features, which are much more powerful and usually have better randomness.
Try this:
int main(int, char **) {
funcs myFunct;
myFunct.createVectorValues();
}
Although no idea why your antivirus is involved. That might be a separate issue.
This question already has answers here:
A method to assign the same value to all elements in an array
(4 answers)
Closed 1 year ago.
I am trying to initialize an empty array that I initialized earlier in the program. However, whenever I compile my program I am given the error
expected an expression (C/C++(29))
Here is what my code looks like:
#include <iostream>
using namespace std;
int main(){
const int MAX_SIZE = 6;
int array[MAX_SIZE] = {12,-3,24,65,92,11};
for(int i=0;i<MAX_SIZE;i++){
cout << array[i] << " ";
}
array[MAX_SIZE] = {};
return 0;
}
The error is indicated right on the first curly brace of the empty array initialization. Also I am using Visual Studio Code on a Mac OS Big Sur.
This expression:
array[MAX_SIZE] = {};
Attempts to assign a value at index 6 to something that isn't an array. That's why it generates a compiler error. (And if it didn't, it would be assigning something to an invalid index in an array!)
You might be temped to think this...
array = {};
...would work, since it's similar for resetting members of objects to a default initialized state. But it doesn't work for arrays.
But this works:
std::fill(a, a+MAX_SIZE, 0); // #include <algorithm> if needed
And will assign every element in a to 0
Old school, "C" way for doing the same thing:
memset(a, '\0', MAX_SIZE*sizeof(int)); // #include <string.h> if needed
Or just manually
for (int i = 0; i < MAX_SIZE; i++) {
a[i] = 0;
}
Your trouble lies here: array[MAX_SIZE] = {};
The initialization syntax only work when you are initializing an array.
Though it does actually compile for me with GCC, the resulting program then crashes.
If you want to fill the array with a value. Either zero or something else, you may want to use std::fill.
Plain C-style arrays are not assignable, the type array[size] = {...}; syntax is only for declaration and initialisation.
You can use std::array<T,N> instead, like this:
#include <array>
#include <iostream>
using namespace std;
int main(){
const int MAX_SIZE = 6;
std::array<int, MAX_SIZE> arr = {12,-3,24,65,92,11};
for(int i=0;i<MAX_SIZE;i++){
cout << arr[i] << " ";
}
// reset all elements back to 0
arr.fill(0);
return 0;
}
#include<iostream>
#include <conio.h>
using namespace std;
struct book
{ int bookid;
char title[20];
float price;
}b2;
int main()
{
b2={100,"c++ by saurabh",105.2}; //values initialised during variable declaration
cout<<"\n"<<b2.bookid;
cout<<b2.title<<" "<<b2.price;
return 0;
getch();
}
This above code shows error in output like this:
C:\Users\shandude\Documents\codeblock\cprog\struct2.cpp|13|error: no match for 'operator=' (operand types are 'book' and '')|
C:\Users\shandude\Documents\codeblock\cprog\struct2.cpp|5|note: no known conversion for argument 1 from '' to 'const book&'|
You can use:
b2 = book{100,"c++ by saurabh",105.2};
PS
I would recommend changing the member variable title to a std::string. Use of char array to represent strings in user code is an anachronism in the year 2017.
struct book
{
int bookid;
std::string title;
float price;
};
What you are doing is not initialization but an assignment, because b2 was already declared earlier. You need to initialize at the point the variable is declared:
struct book
{ int bookid;
char title[20];
float price;
} b2 = {100,"c++ by saurabh",105.2}; //values initialised during variable declaration
int main()
{
cout<<"\n"<<b2.bookid;
cout<<b2.title<<" "<<b2.price;
return 0;
getch();
}
You are trying to initialize b2 by list initialization. You can read the reference to see how to initialize it.
There are many methods. A simple way is:
book b2{100,"c++ by saurabh",105.2};
What complier do you use?
After removing #include <conio.h> and replacing float with double, Clang and VC++ both accept this code while GCC complains. I think it is a bug for GCC.
Although this is not an initialization, it is equivalent to call the assignment operator with the initializer-list as an argument. The parameter of the assignment operator is const book&, and use this initializer-list to initialize this reference is well-defined. The program is also well-defined.
I'm trying to figure out why my code compiles, when it shouldn't:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
constexpr int ret_one()
{
return 1;
}
constexpr int f(int p)
{
return ret_one() * p;
}
int main() {
int i = 2;
srand(time(0));
int j = rand();
int first_array[f(10)]; // OK - 10 is a constant expression
int second_array[f(j)]; // Error - the parameter is not a constant expression
j = f(i); // OK - doesn't need to be constexpr
std::cout << sizeof(second_array);
return 0;
}
So the first_array definition is OK.
But because j is not a constant expression, the second_array definition should be wrong. On each program run I'm getting different array sizes. Is that how it's supposed to work? In my book the author clearly states that a constepxr is an expression whose value can be evaluated at compile time. Can rand() be evaluated at compile time? I think it can't be.
Some compilers, such as GCC, allow C-style variable-length arrays as an extension to C++. If your compiler does that, then your code will compile.
If you're using GCC, then you can enable a warning with -Wvla or -pedantic.
in fact,
int second_array[f(j)];
will use non standard VLA (Varaible length array) extension.
Please help me, I am quite new to C++
I code this in VS 2010
I have a global variable
int avg[SAMPLE][3];
I would like to modify the value in main program by doing something like this:
avg[SAMPLE][3] = {
{30,96,56}, {13,114,55}, {16,118,46},{19,143,64}, {12,129,68},{13,153,69},{15,120,67}
};
However, the VS shows an error: IntelliSense: expected an expression
But it is okay when I declare the value directly to global variable
int avg[SAMPLE][3] = {
{30,96,56}, {13,114,55}, {16,118,46},{19,143,64}, {12,129,68},{13,153,69},{15,120,67}
};
Perhaps this is trivial, but please help me, I am new into C++, and therefore, do not have a clue about it.
Thank you very much.
Re-assigning with an initializer list is not available in C++. C++11 adds this option to classes but not to static C arrays like your example.
What you can do is have one or more const global/static of the value you need and memcpy them when needed:
static const int g_avg[SAMPLE][3] = {
{30,96,56}, {13,114,55}, {16,118,46},{19,143,64}, {12,129,68},{13,153,69},{15,120,67}
};
// usage
int avg[SAMPLE][3];
// ...
memcpy(avg, g_avg, sizeof(avg));
The syntax you used is one that can be used to initialize an array. However, in C/C++, you cannot use that same syntax to assign multiple values to the array. You will have to resort to assigning each value, use a loop, etc.
Just searched a bit more and found a possible duplicate: c++ array assignment of multiple values
Raw (built-in) arrays are not assignable.
However, you can use std::array (fixed size) or std::vector, which are assignable.
It's not a good idea to use global variables. It is a good idea to reserve all uppercase for macro names.
In C++11 (which is not supported by Visual Studio 2010, but you can just get a new free version like Visual Studio 2013),
#include <array>
#include <iostream>
#include <vector>
using namespace std;
struct Sample { int x, y, z; };
auto main()
-> int
{
vector<Sample> avg =
{
{30,96,56}, {13,114,55}, {16,118,46},{19,143,64}, {12,129,68},{13,153,69},{15,120,67}
};
avg = { {1, 1, 1}, {2, 2, 2} };
for( Sample const s : avg )
{
cout << s.x << ", " << s.y << ", " << s.z << endl;
}
}