Question about the efficiency of using an array or individual variables

AI Thread Summary
The discussion centers on the efficiency of using arrays versus individual boolean variables in programming. It suggests that individual variables may offer faster access due to direct addressing, while arrays may benefit from memory caching. The initialization of an array with multiple values is clarified, explaining that using a single initializer only sets the first element, leaving others at zero. Additionally, the conversation highlights the limitations of fixed-size arrays, advocating for dynamic arrays or vectors for user-defined sizes. The complexities of user input handling for dynamic arrays are also addressed, suggesting the use of sentinel values for easier input management.
  • #51
I just started playing with VS recently after a forced move away from Macs to Windows-based machines.

Its not bad and looks to be a powerful competitor to Sublime and Jetbrains IDEs.

The only saving grace was the Ubuntu WSL option. VS can run in both windows and remotely in Ubuntu ie a server runs on Ubuntu to connect to VS for code editing. I haven't gotten it working yet due to air gap reasons but hope to soon.

I did find that you can download extensions for offline installation. MS makes it really easy with a link on the righthand side of the extension summary page and an option in the editor to import extensions from files. Works well unless the extension depends on other extensions and then you have to dig somewhat to figure that out.
 
Technology news on Phys.org
  • #52
pbuk said:
You need to get better at reading error messages. The message says "redefininition of formal parameter 'numSold' on line 23" which clearly tells you all you need to know: on line 23 you redefine numsold which was already defined as a parameter to the function.

Also the code for iterating rows has a number of problems:

C:
       for (row = 1; row < DefaultNSold.size(); row++)
        {
            cout << numSold[row - 1] << " ";
        }

This will miss the last row (think about what happens if size() returns 1). C++ indices start at zero, starting at 1 and then subtracting 1 makes no sense at all - remember what a mess you got into before doing this? It is also not a good idea to use a different array (DefaultNSold) for the limit than the one you are iterating over (numSold) - this makes it difficult to debug (and also makes it almost impossible for the compiler to optimize).

The standard way to write this sort of loop is like this:

C:
    for (int row = 0; row < numSold.size(); row++) {
        cout << numSold[row] << " ";
    }

Oh and for the umpteenth time stop mixing capital letters at the beginning of variable names - (DefaultNSold and numSold). A good convention is to use camelCase for variable names, this means you can save PascalCase for names of classes and structs.

Thanks for the reply, but it's not that simple. I spent hours on this, going through my notes and search on line to verify my syntax was correct, I experimented a lot on each individual pieces before I posted. This is the almost exact program and doesn't give me an error, by just adding "{" and "}" in line 25 and 34. as shown below. But if you run the program below, the content of numSold in the function will not pass back to Sold in the main. That's where I started the trouble shooting.
I experimented individual pieces on passing the function, they all worked, just together it doesn't.

On line 23 where the error is, this is the syntax vector<int>numSold(DefaultNSold); for copying content of vector to another vector. I know it repeat the definition, BUT it will not work if I just put numSold(DefaultNSold); I've gone through all that.

C++:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

void getnumSold(vector<int>&);
vector<int>DefaultNSold = { 842, 416, 127, 514, 437, 269, 97, 492, 212 };

int main()
{
    char key = 'A';
    vector<int>Sold(DefaultNSold.size());//recieve number sold for each item.
    getnumSold(Sold);//passing vector Sold to function getnumSold().
    cout << "In main return from getnumSold Sold = {";
    for (int i = 0; i < 9; i++)
        cout << Sold[i] << " ";
    cout << "} \n\n";
    return 0;
}void getnumSold(vector<int>& numSold)
{

    {
        int row;
        vector<int>numSold(DefaultNSold);
        cout << " In getnumSold, You chose to use default = {";
        for (row = 1; row < DefaultNSold.size(); row++)
        {
            cout << numSold[row - 1] << " ";
        }
        cout << numSold[row - 1] << "}\n\n";
    }
}

About the row =1 to row < size-1, It was NOT the complete program as I tried to cut all the irrelevant lines to make the program as short to read as possible. You can see the more complete program I put in this time. The reason is I need to put "}" AFTER the last number(shown in line 33), I cannot put this in the loop. So I use one extra line to put in the last number. Note that row++ after exit from the for loop. Line 33 points to the last element.

I spent a lot of hours on this before I posted, I know better to check everything first. This is really funky.

Thanks
 
Last edited:
  • #53
This is the original program before I started cutting lines to simplify for posting here. It compiles but parameters won't pass that started the whole thing. It's too long for anyone to read through all the irrelevant lines. It's not complete, I even blocked out some part that doesn't pertain to the problem.

From working on this, I have the suspicion that copying vector using vector<int>numSold(DefaultNSold) with passing parameter with & to the function together that gives the problem. I experimented individually, they all worked, just together that's when problem starts.

I know I can put the vectors in global where everyone can access will work. But I want to practice passing parameters with reference. This is to me very important for future.

I know using array will work a lot easier and I did that already, but that's not the point. I want to practice on passing reference vectors.

C++:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

void getnumSold(vector<int>&);
void getProdNum(int &);
void Bsearch(int[], int size, int num, int &);
//void displayProd(vector<int>&);

const int Row = 9, ProdCol = 31;
char Prod[Row][ProdCol] = { {"Six Steps to Leadership"}, {"Six Steps to Leadership"}, {"Road to Exellence"},
                {"Seven Lessons of Quality"},{"Seven Lessons of Quality"},{"Seven Lessons of Quality"},
                {"Teams Are Made, Not Born"}, {"Leadership for the Future"}, {"Leadership for the Future"} };

char Desc[Row][ProdCol] = { {"Book"}, {"Audio CD"}, {"DVD"},
                {"Book"}, {"Audio CD"}, {"DVD"},
                {"Book"}, {"Book"}, {"Audio CD"} };

float Price[] = { 12.95, 14.95, 18.95, 16.95,
                21.95, 31.95, 14.95, 14.95, 16.95 };

int pnAr[] = { 914, 915, 916, 915, 918,//   0, 1, 2, 3, 4
              919, 920, 921, 922 };//        5, 6, 7, 8

vector<int>DefaultNSold = { 842, 416, 127, 514, 437, 269, 97, 492, 212 };

int main()
{
    char key = 'A';
    vector<int>Sold(DefaultNSold.size());//recieve number sold for each item.
    int partNum;// part number of the book from customer.
    getnumSold(Sold);//passing vector Sold to function getnumSold().
    cout << "In main return from getnumSold Sold = {";
    for (int i = 0; i < 9; i++)
        cout << Sold[i] << " ";
    cout << "} \n\n";
    //displayProd(Sold);//Show all the tittles of the items
    return 0;
}

/*void displayProd(vector<int>&Sold)// display the table of selections and price.
{
    cout << left << setw(35) << "     Product" << setw(15) << "Decription" << setw(10) << "Part num" <<
    setw(15) << "   Price" << setw(10) << "sold" << "\n\n";
    for (int line = 0; line < Row; line++)
    {
        cout << "  " << left << setw(35) << Prod[line] << left << setw(15) <<
        Desc[line] << setw(10) << pnAr[line] << "$" << Price[line] <<
        right << setw(10) << Sold[line] << "\n\n";
    }
}*/

void getnumSold(vector<int>& numSold)
{
    char select;
    cout << " Enter y to use default numbers, any other character";
    cout << "for entering 6 new numbers: "; cin >> select;
    if ((select == 'y') || (select == 'Y'))
    {
        int row=1;
        vector<int>numSold(DefaultNSold);  
        cout << " In getnumSold, You chose to use default = {";
        for (row = 1; row < DefaultNSold.size(); row++)
        {
            cout << numSold[row - 1] << " ";
        }
        cout << numSold[row - 1] << "}\n\n";
    }
    else
    {
        cout << " You chose to enter 9 new sales number.\n\n";
        cout << "Enter number sold for the following\n\n";
        for (int row = 1; row <= DefaultNSold.size(); row++)
        {
            cout << "   " << left << setw(35) << Prod[Row-1] << left <<
                setw(15) << Desc[row-1] << "$" << Price[row-1] << " is:   ";
            cin >> numSold[row-1];
        }
    }
}
 
Last edited:
  • #54
I think there's something wrong with this vector<int>numSold(DefaultNSold). I wasted a day on this, now I just do it the dumb way and works like a champ:
C++:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

void getnumSold(vector<int>&);
vector<int>DefaultNSold = { 842, 416, 127, 514, 437, 269, 97, 492, 212 };

int main()
{
    char key = 'A';
    vector<int>Sold(DefaultNSold.size());//recieve number sold for each item.
    getnumSold(Sold);//passing vector Sold to function getnumSold().
    cout << "In main return from getnumSold Sold = {";
    for (int i = 0; i < 9; i++)
        cout << Sold[i] << " ";
    cout << "} \n\n";
    return 0;
}void getnumSold(vector<int>& numSold)
{
int row = 1;
cout << " In getnumSold, You chose to use default = {";
for (row = 1; row < DefaultNSold.size(); row++)
{
    numSold[row - 1] = DefaultNSold[row - 1];
    cout << numSold[row - 1] << " ";
}
numSold[row - 1] = DefaultNSold[row - 1];
cout << numSold[row - 1] << "}\n\n";

}

I just use for loop to copy DefaultNSold to numSold. No problem passing back the parameter from function to main. Everything works. What a waste of time trying a new "more convenient" instruction. I don't think in real time operation, the vector<int>numSold(DefaultNSold) is any more efficient than a for loop.

I've been on line searching, I cannot find anything on vector<int>numSold(DefaultNSold). I saw plenty examples using for loop to copy.

There's something to be said NOT to try to be fancy just to save a line, do it the primitive and dumb way might end up getting ahead. I might have finish chapter 8 if I were not trying to be fancy. This is my philosophy in my whole career and served me well. Do it simple, do it reliable and do it fast. Don't try to save a penny and lose a pound.
 
Last edited:
  • #55
Efficiency is seldom on the mind of a programmer with a deadline and some requirements. Often we will write code so that it is easily maintainable.

Other times we will code in constants thinking that'll never change and since we're in a hurry let's move on to darn I wish I coded it as a named constant as you scan through your code trying to decide the linkages of one constant value to another.

Fancy operators and cute tricks are replaced by more reliable easily read code. In C and C++ there was a contest on code obsfucation ie how to make the most compact and unreadable c code which involved one letter variable names, removal of spaces and newlines, and operator tricks to further confuse.

The ++ pre and post operators can make some interesting reading as compilers differ as to how they are interpreted. As an example, (++x - x++) = ? where x is some integer.

Some odd examples are found within these "rules" for C and C++:

https://rules.sonarsource.com/cpp
 
  • #56
yungman said:
Thanks for the reply, but it's not that simple.
I know that when you can't see the problem it doesn't look simple, but it really is.

yungman said:
I spent hours on this, going through my notes and search on line to verify my syntax was correct,
If your syntax was wrong then it would have said 'Syntax error', not told you about trying to define a variable twice.

yungman said:
I experimented a lot on each individual pieces before I posted. This is the almost exact program and doesn't give me an error, by just adding "{" and "}" in line 25 and 34. as shown below. But if you run the program below, the content of numSold in the function will not pass back to Sold in the main. That's where I started the trouble shooting.
It doesn't give you an error because by adding { and } you have created an inner scope where you can declare variables that are only visible within that scope. So it allows you to redefine numSold and work with it, but as soon as it reaches the end of that inner scope the new numSold is forgotton.

I suggest you stop working on this and move on and learn some more C++. You need to get on to the chapters on structs, classes and pointers because at the moment you are like the man trying to hit a screw in with a hammer because he hasn't learned about screwdrivers yet.

yungman said:
About the row =1 to row < size-1, It was NOT the complete program as I tried to cut all the irrelevant lines to make the program as short to read as possible. You can see the more complete program I put in this time. The reason is I need to put "}" AFTER the last number(shown in line 33), I cannot put this in the loop. So I use one extra line to put in the last number. Note that row++ after exit from the for loop. Line 33 points to the last element.
In that case you simply need to do:
C++:
   for (int row = 0; row < numSold.size() - 1; row++) {
        cout << numSold[row] << " ";
    }
    cout << numSold[row] << "}\n\n";
 
  • #57
jedishrfu said:
The ++ pre and post operators can make some interesting reading as compilers differ as to how they are interpreted.
That is not true, all compilers stick to the standard.
jedishrfu said:
As an example, (++x - x++) = ? where x is some integer.
That is not a difference in implementation of ++x or x++, that is a difference in whether the compiler process the left half or right half of the expression first - and the C++ standard states that this is not defined i.e. the compiler can decide which to do first - and can even leave the order decision to run time and do it differently each time.
 
  • #58
  • #59
pbuk said:
I know that when you can't see the problem it doesn't look simple, but it really is.If your syntax was wrong then it would have said 'Syntax error', not told you about trying to define a variable twice.
Because my syntax was not wrong.
pbuk said:
It doesn't give you an error because by adding { and } you have created an inner scope where you can declare variables that are only visible within that scope. So it allows you to redefine numSold and work with it, but as soon as it reaches the end of that inner scope the new numSold is forgotton.
I figured that much already.

pbuk said:
I suggest you stop working on this and move on and learn some more C++. You need to get on to the chapters on structs, classes and pointers because at the moment you are like the man trying to hit a screw in with a hammer because he hasn't learned about screwdrivers yet.
So there is no fix on this other than quit using vector<int>set1(set2) with function passing vector as reference? This is NOT about hitting screw with hammer, it's a matter either I did something wrong that I don't know, or something is wrong with the that line. I know one can NOT pass parameter without declaring
void getnumSold( vector<int>&numSold). Also one has to write vector<int>numSold(DefaultNSold) in order to copy from DefaultNSold into numSold . So this is catch 22. I know this is a problem. How do people solve this?

pbuk said:
In that case you simply need to do:
C++:
   for (int row = 0; row < numSold.size() - 1; row++) {
        cout << numSold[row] << " ";
    }
    cout << numSold[row] << "}\n\n";
I want row to represent the real row number. The way I do works.
 
  • #60
jedishrfu said:
Efficiency is seldom on the mind of a programmer with a deadline and some requirements. Often we will write code so that it is easily maintainable.
That's exactly what is so wrong with all the new products that use embedded software/firmware, computers, printers and all that. As the processor speed gets faster, memory gets bigger, things are getting slower and slower( I mean literally), things gets more and more unreliable. This is my experience with laptops, printers, smart tv, cars. Literally anything that involves computer. I have all name brand stuffs, the most sickening things is I had the same brand older models and they ALL WORKED. BUT when I bought the newer models, they suck to holy hell. the car, the printer, the tv, you name it.
I had a 2003 Mercedes E class, it was so reliable and so good. Lasted 15 years and was still good when we got rid of it. I bought a 2014 Mercedes ML, never been to the shop yet. We love them so much and bought a 2018 E class. It was in the shop over 5 weeks in the first 8 months all because of computer problems. The response with everything is so so slow. When the computer is doing something, everything else stops! You try to do simple things like shifting the transmission from D to R, it will take 3 sec to do. Try to make a 3 point turn on a busy street! Problems never got fixed, we just gave up.

then the printers, even my Samsung LED tv. My 65" works perfectly, my new 82" is something else. Color is wrong, had an intermittent issue I am still trying to track. I went through 5 or 6 printers in the last 3 years. They are all so intermittent.

jedishrfu said:
Other times we will code in constants thinking that'll never change and since we're in a hurry let's move on to darn I wish I coded it as a named constant as you scan through your code trying to decide the linkages of one constant value to another.

Fancy operators and cute tricks are replaced by more reliable easily read code. In C and C++ there was a contest on code obsfucation ie how to make the most compact and unreadable c code which involved one letter variable names, removal of spaces and newlines, and operator tricks to further confuse.

The ++ pre and post operators can make some interesting reading as compilers differ as to how they are interpreted. As an example, (++x - x++) = ? where x is some integer.

Some odd examples are found within these "rules" for C and C++:

https://rules.sonarsource.com/cpp
I said this before, I might be new in programming, I have been the chief EE and manager of EE for decades in real world in environment of the company sink or swim depending on the success of the product I designed. I hold dearly the philosophy of make it simple, make it reliable and do it fast. In hardware, a line of code is like a component that actually cost money. I still push my group to design is the most straight forward way, the most reliable way. Don't get fancy, that the success is measure on how reliable the product, deliver on time. NOT how "wise" is the circuit design.

the new stuffs are NOT convenient, it's a headache to use. Just no choice, things are not made to last, you have to buy new ones. I just gave away my 72" Mitsubishi rear projection tv that lasted 15 years. The color is a MILE better than the fancy Samsung LED tvs( I mean all of them). I had to gave it away because it's too big. I am very into top end hifi, the big Mitsubishi is blocking the sound and make the living room looks busy. I had to give it away and replace it with a 82" LED tv. That was a downgrade. BUT, the sound of my hifi got a lot better.
 
  • #61
One reason for code bloat is the use of libraries that do what you want and more. Unfortunately, sometimes you can't just discard the more part.

One example from my recent past is developing code in python using Anaconda. Python modules call in other python modules so while you may want some particular function in a given module. It will pull in other modules you don't need.

The upside of using other peoples code is that you don't have to write it only use it as it probably had better testing done depending on its maturity of course.

We code to fit into the hardware we have and if we need a lot less memory then it can be engineered out of the final product. But wait, we may need to patch or update the code and we may need that memory that was removed so we must balance out our tradeoffs.

The old programming mantra still holds:
_ I can make it fast
- I can make it cheap
- I can make it reliable

pick any two and let me know.

Of course, bosses today will pick two and then ding you on the one they didn't choose.

Its good that you have an engineering background but sometimes that will get in the way of software development.

On one project I worked on, the engineers saved money on a signal pattern generator for high speed memory testing by packing the internal looping code ie by using 14 bit counters in one place and 12 bit in another...

It was a bear for programmers to build loop code loads as we had to constantly pack stuff up and decode errors returned to figure out what was happening during a test.

The hardware design didn't factor in the programmer's needs in the interest of getting the cheapest and fastest hardware possible.

I remember one hardware manager showing empathy to the programmers by saying he once wrote a BASIC program and can understand the difficulties we faced. We just looked at each other.

Some of the engineers in our group looked down on the programmers too. We needed to test a C based monitoring program that handled 200 sensors in a bay continuously for a few days. However, every morning we discovered it was swapped out for a PC BASIC program.

When asked why the engineers said our program ran too slow for their needs. Upon further investigation, we discovered that their program ran faster because it monitored only 20 sensors continuously. What a crock? Ours was configurable and could have done the same if they told us.

The payback came when they had some test program written in BASIC that exceeded 64K (PC-DOS BASIC limit) and they wanted our help to fix it. We suggested removing comments and other memory saving tricks but to no avail. Finally we said well I guess you'll have to recode it in C like we told you months ago. They were not happy campers after that.
 
  • #62
Ha, I never told programmers what to do, they tell me what they need and I design to fit their needs! They are the one that have to make the system work, Hardware part is only to support the system. Unless it is impossible for us to meet their needs, I always try to give them what they want. I sure did not tell them what language to write! What do I know!

I did a little assemble language programming long time ago, at least I know enough how to design hardware to make lives easier for people that are going to program it. Remember, we can make the most reliable hardware, but if programmer cannot program it, it's still a big fat ZERO. So part of my task is to make programmers' lives easier if all possible. It was always very smooth, never ran into problem in that department.

My specialty is really analog, RF, low noise. I had to design MPU digital stuffs only because I was the only one that can do it. It's not like I did those every day. Just design when needed. I designed the hardware, wrote the specifications how to program it. Never once I heard back from the software people after I handed it over. Maybe I was lucky!
 
  • Like
Likes jedishrfu
  • #63
Back to the original question, is there any way to fix using function
void getnumSold( vector<int>&numSold) and use vector<int>numSold(DefaultNSold) to copy DefaultNSold into numSold and then allow main to access as reference?

thanks
 
  • #64
yungman said:
So there is no fix on this other than quit using vector<int>set1(set2) with function passing vector as reference? This is NOT about hitting screw with hammer, it's a matter either I did something wrong that I don't know, or something is wrong with the that line. I know one can NOT pass parameter without declaring
void getnumSold( vector<int>&numSold). Also one has to write vector<int>numSold(DefaultNSold) in order to copy from DefaultNSold into numSold . So this is catch 22. I know this is a problem. How do people solve this?

What you did wrong is exactly what the error message said.

Also one has to write vector<int>numSold(DefaultNSold) in order to copy from DefaultNSold into numSold . So this is catch 22. I know this is a problem. How do people solve this?

What that does is not just copy. It is making a whole new vector, numSold (using the same name as the parameter, hence the error message). I think your confusion will be cleared up when you learn about classes. You didn't learn what a constructor is yet, and were using it without even knowing it, thinking it was something else.

Anyways, I guess this is what you wanted to do (use the assignment operator):

Code:
void getnumSold(vector<int>& numSold)
{
    numSold = DefaultNumSold;
}

Also, it might be a good time to do a google search: "why are global variables considered bad programming practice".
 
Last edited:
  • #65
I put in the line you suggested, it's NOT working, it won't even compile. Also, I specifically asked about how to use vector<int>numSold(defaultNSold) for copying. I know numSold was defined TWICE, one in the function declaration, one in vector<int>numSold(defaultNSold). But this is how the syntax has to be. I am not asking about the error information. I know what is the error. My question is HOW to fix it using vector<int>numSold(defaultNSold).

This is what you suggested, it won't compile. I know how to fix the problem and I already fixed it using simple for loop.
C++:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

void getnumSold(vector<int>&);
vector<int>DefaultNSold = { 842, 416, 127, 514, 437, 269, 97, 492, 212 };

int main()
{
    char key = 'A';
    vector<int>Sold(DefaultNSold.size());//recieve number sold for each item.
    getnumSold(Sold);//passing vector Sold to function getnumSold().
    cout << "In main return from getnumSold Sold = {";
    for (int i = 0; i < 9; i++)
        cout << Sold[i] << " ";
    cout << "} \n\n";
    return 0;
}void getnumSold(vector<int>& numSold)
{
int row = 1;

    numSold = DefaultNumSold;

cout << " In getnumSold, You chose to use default = {";
for (row = 0; row < DefaultNSold.size(); row++)
{
    cout << DefaultNumSold[row] << " ";
}
cout << numSold[row] << "}\n\n";

}
 
  • #66
yungman said:
Because my syntax was not wrong.

I figured that much already.So there is no fix on this other than quit using vector<int>set1(set2) with function passing vector as reference? This is NOT about hitting screw with hammer, it's a matter either I did something wrong that I don't know, or something is wrong with the that line. I know one can NOT pass parameter without declaring
void getnumSold( vector<int>&numSold). Also one has to write vector<int>numSold(DefaultNSold) in order to copy from DefaultNSold into numSold . So this is catch 22. I know this is a problem. How do people solve this?I want row to represent the real row number. The way I do works.
yungman said:
I put in the line you suggested, it's NOT working, it won't even compile. Also, I specifically asked about the code vector<int>numSold(defaultNSold) for copying. I know numSold was defined TWICE, one it the function declaration, one in vector<int>numSold(defaultNSold). But this is how the syntax has to be. I am not asking about the error information. I know what is the error. My question is HOW to fix it using vector<int>numSold(defaultNSold).

This is what you suggested, it won't compile.
C++:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

void getnumSold(vector<int>&);
vector<int>DefaultNSold = { 842, 416, 127, 514, 437, 269, 97, 492, 212 };

int main()
{
    char key = 'A';
    vector<int>Sold(DefaultNSold.size());//recieve number sold for each item.
    getnumSold(Sold);//passing vector Sold to function getnumSold().
    cout << "In main return from getnumSold Sold = {";
    for (int i = 0; i < 9; i++)
        cout << Sold[i] << " ";
    cout << "} \n\n";
    return 0;
}void getnumSold(vector<int>& numSold)
{
int row = 1;

    numSold = DefaultNumSold;

cout << " In getnumSold, You chose to use default = {";
for (row = 0; row < DefaultNSold.size(); row++)
{
    cout << DefaultNumSold[row] << " ";
}
cout << numSold[row] << "}\n\n";

}
What you are saying doesn't make any sense.
 
  • #67
Jarvis323 said:
What you are saying doesn't make any sense.
This is what you suggested to do: numSold = DefaultNumSold; It won't even compile.

I am not asking HOW to copy the vector from DefaultNSold to numSold, there are ways to do that. I specifically asked about using vector<int>numSold(defaultNSold) line to copy when passed to the function. This is in the book. It works if it is not passing into a function.

I already use a simple for loop to copy and completed the program already.

 
  • #68
yungman said:
This is what you suggested to do: numSold = DefaultNumSold; It won't even compile.

I am not asking HOW to copy the vector from DefaultNSold to numSold, there are ways to do that. I specifically asked about using vector<int>numSold(defaultNSold) line to copy when passed to the function. This is in the book. It works if it is not passing into a function.

I already use a simple for loop to copy and completed the program already.

If you read the error message of the new code where you used the assignment operator, you'll see that this is the error message.
Code:
prog.cpp:26:15: error: ‘DefaultNumSold’ was not declared in this scope
     numSold = DefaultNumSold;

It's because I wrote DefaultNumSold instead of DefaultNSold.

yungman said:
I specifically asked about using vector<int>numSold(defaultNSold) line to copy when passed to the function. This is in the book. It works if it is not passing into a function.

I already use a simple for loop to copy and completed the program already.

Like I said, that doesn't make sense at all. It isn't code for copying like you think it is, read my previous post again. Your problem is you don't understand what the line of code means. Once you understand what that code means, you'll realize your mistake and that it has nothing to do with it being passed to a function or not. Here is an equivalently wrong program without a function.

Code:
vector< int > x;
vector< int > &  y = x;
vector< int > y = default;

You need to slow down and learn what the code you are writing actually means, not just what you expect it to do.
 
Last edited:
  • Like
Likes pbuk
  • #69
Jarvis323 said:
Like I said, that doesn't make sense at all to do. Your problem is you don't understand what the line of code means, which I explained to you. Once you understand what that code means, you'll realize your mistake. It has nothing to do with it being passed to a function or not. Here is an equivalently wrong program without a function.

Code:
vector< int > x;
vector< int > &  y = x;
vector< int > y = default;
Jarvis323 said:
I understand the lines of code, I need to define the function
void getnumSold(vector<int>& numSold)

AND

I have to follow the instruction from the book vector<int>numSold(defaultNSold)

That defined the vector twice and thereby have the error. BUT I experimented the line of code vector<int>numSold(defaultNSold), it works as long as it's not passed to function. It WON'T work when passing the function.

These are very specific syntax and they don't work together. My question is how can I make this work. NOT how to do it.
 
  • #70
You can't make it work because it doesn't make any sense. If you want a new variable, then just use a different name. It won't be the same variable of course. It doesn't make a difference whether it's inside a function or not, you can't use the same name for two different variables. If it worked for you outside a function, then that's not what you did. Here are some examples.

C:
// this is wrong
vector< int > x;
vector< int > &  y = x;
vector< int > y( d ); // the name y is already used

// this is also wrong
vector< int > x;
vector< int > x; // the name x is already used

// this is also wrong
vector< int > x;
vector< int > x( d ); // the name x is already used

// this is also wrong
vector< int > x;
vector< int > x = d;// the name x is already used

// this is correct
vector< int > x = d;

// this is correct and exactly equivalent to the last version
vector< int > x (d);

// this is correct as well
vector< int > x;
x = d;

And it's not because it's a vector either.

C:
// this is wrong
int x;
int &  y = x;
int  y( d ); // the name y is already used

// this is also wrong
int x;
int x; // the name x is already used

// this is also wrong
int x;
int x( d ); // the name x is already used

// this is also wrong
int x;
int x = d;// the name x is already used

// this is correct
int x = d;

// this is correct
int x (d);

// this is correct as well
int x;
x = d;
 
Last edited:
  • #71
Jarvis323 said:
You can't make it work because it doesn't make any sense. If you want a new variable, then just use a different name. It won't be the same variable of course. It doesn't make a difference whether it's inside a function or not, you can't use the same name for two different variables. If it worked for you outside a function, then that's not what you did. Here are some examples.

C:
// this is wrong
vector< int > x;
vector< int > &  y = x;
vector< int > y( d ); // the name y is already used

// this is also wrong
vector< int > x;
vector< int > x; // the name x is already used

// this is also wrong
vector< int > x;
vector< int > x( d ); // the name x is already used

// this is also wrong
vector< int > x;
vector< int > x = d;// the name x is already used

// this is correct
vector< int > x = d;

// this is correct and exactly equivalent to the last version
vector< int > x (d);

// this is correct as well
vector< int > x;
x = d;

And it's not because it's a vector either.

C:
// this is wrong
int x;
int &  y = x;
int  y( d ); // the name y is already used

// this is also wrong
int x;
int x; // the name x is already used

// this is also wrong
int x;
int x( d ); // the name x is already used

// this is also wrong
int x;
int x = d;// the name x is already used

// this is correct
int x = d;

// this is correct
int x (d);

// this is correct as well
int x;
x = d;
I know what you are talking all along. I cannot make it work because the code vector<int>numSold(defaultNSold) cannot work in all situation, maybe that's answer to my question already, I cannot use this to copy vector in the function where I have to define the vector in the function parameters.
 
  • #72
yungman said:
I know what you are talking all along. I cannot make it work because the code vector<int>numSold(defaultNSold) cannot work in all situation, maybe that's answer to my question already, I cannot use this to copy vector in the function where I have to define the vector in the function parameters.
No. It has nothing to do with functions or function parameters, or vectors, or copying. It's much much simpler and the same in every single case. You cannot declare two completely separate variables with the same name in the same scope. It's exactly the same reason you cannot do, int x; int x;, it's not that you cannot use int x; in some special case, it's that the name is already used. You can't do it in any case. Again, the copy constructor is not a copy function. It creates a another variable that is initialized based on the value of the other one.
 
  • #73
Here is an analogy that hopefully makes sense.

You go and buy a blender. You read the instructions. It says, to use the blender:

1) unpack the blender from the packaging
2) plug it in
3) press the on button

Later on, after you've already unpacked it and have used it once, you decide to move the blender into a new room. And then you want to turn it on. You read the instructions again, how to turn it on. But you find you cannot (1) unpackage the blender, because the packaging is gone. So your solution is you go to the store, buy a new blender, unpack that one, plug that one in, and press its on button. But the old blender is still not on. So you complain. How can I make my old blender work by buying a new blender, unpacking it and turning it on?

The answer is you can't, it's a different blender. The solution is to just plug the old blender in, and it doesn't make sense to unpack and already unpacked blender.
 
  • #74
Jarvis323 said:
Here is an analogy that hopefully makes sense.

You go and buy a blender. You read the instructions. It says, to use the blender:

1) unpack the blender from the packaging
2) plug it in
3) press the on button

Later on, after you've already unpacked it and have used it once, you decide to move the blender into a new room. And then you want to turn it on. You read the instructions again how to turn it on. But you find you cannot (1) unpackage the blender, because the packaging is gone. So your solution is you go to the store, buy a new blender, unpack that one, plug that one in, and press its on button. But the old blender is still not on. So you complain. How can I make my old blender work by buying a new blender, unpacking it and turning it on?

The answer is you can't, it's a different blender. The solution is to just plug the old blender in, and it doesn't make sense to unpack and already unpacked blender.
I know, it won't work. That's my conclusion already.
 
  • #75
I finally finish the program using the dumb way to copy vector. Works like a champ. I made it a lot fancier, instead of following the book use given set of number sold for each product, I can input the numbers as wish by user. then display the description, price, #sold and total dollar sold for each item and sort with the highest dollar amount first.
C++:
// This program display the title of the product, the unit cost and the total sales in 6 months
// And sort in the order of the highest dollar sales product first to the least.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

void getnumSold(vector<int>&); //To input the number of unit sold in 6 months, you can choose to input the number or use default.
void displayProd(vector<int>&, vector<float>);//displace the list of product and their cost.
void DollarSales(vector<int>&, vector<float>&);//Calculate the total dollar sold for each item.
void sortSales(vector <float>, vector<int>&);// Sort with highest dollar sold first.
void displaySales(vector<int>, vector<float>, vector<int>);// Display in order of the highest dollar sold first.const int Row = 9, ProdCol = 31;
char Prod[Row][ProdCol] = { {"(0)Six Steps to Leadership"}, {"(1)Six Steps to Leadership"}, {"(2)Road to Exellence"},
                {"(3)Seven Lessons of Quality"},{"(4)Seven Lessons of Quality"},{"(5)Seven Lessons of Quality"},
                {"(6)Teams Are Made, Not Born"}, {"(7)Leadership for the Future"}, {"(8)Leadership for the Future"} };

char Desc[Row][ProdCol] = { {"Book"}, {"Audio CD"}, {"DVD"},
                {"Book"}, {"Audio CD"}, {"DVD"},
                {"Book"}, {"Book"}, {"Audio CD"} };

float Price[] = { 12.95, 14.95, 18.95, 16.95,
                21.95, 31.95, 14.95, 14.95, 16.95 };

int pnAr[] = { 914, 915, 916, 915, 918,//   0, 1, 2, 3, 4
              919, 920, 921, 922 };//        5, 6, 7, 8

vector<int>DefaultNSold = { 842, 416, 127, 514, 437, 269, 97, 492, 212 };

int main()
{
    vector<int>itemNum = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };//Item number from 0 to 8
    vector<int>Sold(DefaultNSold.size());//recieve number sold for each item.
    vector<float>totalValue(DefaultNSold.size());
    getnumSold(Sold);//passing vector Sold to function getnumSold(). Return of #sold of each item
    DollarSales(Sold, totalValue); // pass #sold in vector Sold, and return total sold value of each item.
    displayProd(Sold, totalValue);//Show all the tittles of the items
    sortSales(totalValue, itemNum);// pass total sold value of each item to sort highest to lowest total $ of items.
                                    // also return the order of the items from highest to lowest for sorting.
    displaySales(Sold, totalValue, itemNum);// Display from highest to lowest the total sales of items.
    return 0;                    
}

void getnumSold(vector<int>& numSold)// get and return vector numSold to vector Sold
{
    char select;
    cout << " Enter y to use default numbers, any other character";
    cout << "for entering 6 new numbers: "; cin >> select;
    if ((select == 'y') || (select == 'Y'))
    {
        int row=1;
        cout << " In getnumSold, You chose to use default = {";
        for (row = 1; row < DefaultNSold.size(); row++)
        {
            numSold[row - 1] = DefaultNSold[row - 1];
            cout << numSold[row - 1] << " ";
        }
        numSold[row - 1] = DefaultNSold[row - 1];
        cout << numSold[row - 1] << "}\n\n";
    }
    else
    {
        cout << " You chose to enter 9 new sales number.\n\n";
        cout << "Enter number sold for the following\n\n";
        for (int row = 1; row <= DefaultNSold.size(); row++)
        {
            cout << "   " << left << setw(35) << Prod[Row-1] << left <<
                setw(15) << Desc[row-1] << "$" << Price[row-1] << " is:   ";
            cin >> numSold[row-1];
        }
    }
}
void displayProd(vector<int>& Sold, vector<float>totVal)// display the table of selections and price.
{
    cout << " In displayProd\n\n";
    cout << left << setw(35) << "     Product" << setw(15) << "Decription" << setw(10) << "Part num" <<
        setw(15) << "   Price" << setw(10) << "sold" << setw(17) << "total" << "\n\n";
    for (int line = 0; line < Row; line++)
    {
        cout << "  " << left << setw(35) << Prod[line] << left << setw(15) <<
            Desc[line] << setw(10) << pnAr[line] << "$" << Price[line] <<
            right << setw(10) << Sold[line] << setw(7) <<"$" << left <<  totVal[line] << "\n\n";
    }
}
void DollarSales(vector<int>&Sold, vector<float>&totalValue)// receive vector Sold and vector itemNum.
{                                                   // return to vector Sold.
    int size = Sold.size();
    for (int element = 0; element < size; element++)
    {
        totalValue[element] = Price[element] * Sold[element];
        //cout << totalValue[element] << "\n\n";
    }
}
void sortSales(vector <float>Ar, vector<int>& itemN)// receive vector Sold and vector itemNum.
//function return vector itemN that contain the order of the items sorted from lowest
// total sales to highest.
{
    int size = Ar.size();// find the size of the vector. 
    int startScan = 0, index, temp2;
    float temp1;
    do
    {
        index = startScan + 1; // startScan is the first element number, index is the following number.
        while (index < size)
        {
            if (Ar[startScan] < Ar[index])//comparing the lowest number element starting with AR[0] to the rest
            {                    // one by oneswitch with them if it is higher than the other elements.
                temp1 = Ar[startScan];    temp2 = itemN[startScan];
                Ar[startScan] = Ar[index];    itemN[startScan] = itemN[index];
                Ar[index] = temp1; itemN[index] = temp2;
            }
            index = index + 1;// to the next lower element to compare,  AR[1]->AR[2]-> AR[3]...
        }
        startScan = startScan + 1;
    } while (startScan < (size - 1));
}
void displaySales(vector<int>Sold, vector<float>totalValue, vector<int> itemN)
{
    cout << "\n\n\n\n After sorting with the highest dollar amount first \n\n";
    cout << left << setw(35) << "     Product" << setw(15) << "Decription" << setw(10) << "Part num" <<
    setw(15) << "   Price" << setw(10) << "sold" << setw(17) << "total" << "\n\n";
    int Row = Sold.size();
    for (int line = 0; line < Row; line++)
    {
        cout << "  " << left << setw(35) << Prod[itemN[line]] << left << setw(15) <<
            Desc[itemN[line]] << setw(10) << pnAr[itemN[line]] << "$" << Price[itemN[line]] <<
            right << setw(10) << Sold[itemN[line]] << setw(7) << "$" << left << totalValue[itemN[line]] << "\n\n";
    }
}

I am done with Chapter 8, this is a lot more difficult than any problem in the book on chapter 8. I use a lot of vectors instead of arrays so to make it easier to expand the number of items as needed. Only the old ones are in array that I did not convert to vectors.

I only put the text display arrays in global section, those are not going to be changed. All the vectors that the program work on are parameters passing to function from main. They stay local as much as possible. The program is calling function to do everything, the main is only about 12 lines.
 
Last edited:
  • #76
jedishrfu said:
The old programming mantra still holds:
_ I can make it fast
- I can make it cheap
- I can make it reliable

pick any two and let me know.

Of course, bosses today will pick two and then ding you on the one they didn't choose.

Never truer words spoken...
 
  • #77
For memory efficiency:

C++:
struct boolmap {
    char x:1;
    char y:1;
    char z:1;
};
 
  • #78
Dr Transport said:
Never truer words spoken...
I assume make it fast meaning the speed, not deliver the program fast. One thing I always told my people, do NOT rush, don't wait until the last minute to do the job. Take the time to do it right, think it out first, don't rush in.

I am proud to say in my career, hardware always ahead of schedule way before the mechanical and software group. I hate the marketing schedule, they think if they put in unrealistic schedule, they can pressure people to work faster. Nothing is more time wasting than doing it wrong, then having to bandage it back. That's wasting money, wasting time.

I monitor my people, make sure they take the time to do it right, quality control right from the beginning. Might have a slow start, but we always finish ahead.

Back to the 3 options: make it fast( as running speed), I pick 1 and 3 any time of the day. I talked about this many times here already how frustrating that the newer stuffs are getting slower and stupider. Too many fancy feature in the name of nobody left behind, that even the stupidest people can stumble through. I want things to respond fast. I want things that work. Nothing is more frustrating than my 2 year old car spent over 5 weeks in the shop the first 8 months ALL software problems. All the intermittents and lockups.

Nothing costs more money than a bad design and resort to bandage it up, then bandage the bandage.
 
  • #79
One thing that is way off the subject but is of utmost important for reliability...Programming FPGA. Software people might look at VHDL or AHDL( Altera's own language) and think it's easy as it looks like any computer language......Don't even think about it. The language is almost the same, but the effect is totally different. The difference is in software, everything is working is sequence, one step at a time. FPGA signal are working in PARALLEL. You might think you program one step at a time, but all steps are working at the same time in FPGA. If software people want to move into FPGA programming, make sure to take a basic digital class first, learn about timing and all before they even touch this. So many mistake are made because people don't understand. I wrote FPGA programming because I understand digital hardware. I program as if it is a circuit, not a program. I had to troubleshoot problems with FPGAs written by someone else. Any language is only a tool, it's only a means to an end. Have to know to big picture.

Funny in my gym, one guy was the top dog manager in Lockheed at the time, we were talking about about circuit design and topic landed on FPGA, when I was telling him all the trouble I had to go through troubleshooting the glitches from FPGAs, he offered me a job on the spot! I was laughing! I retired already, I have no intention of working again.
 
  • #80
I have a question on initialize pointer. The books said it's illegal to do this:
C++:
float myFloat;
int *pint = &myFloat;

I understand myFloat is a float, not an int. But the starting address of the variable myFloat is an int. Why can't you initialize int *pint to the address of myFloat?
 
  • #81
yungman said:
I have a question on initialize pointer. The books said it's illegal to do this:
C++:
float myFloat;
int *pint = &myFloat;

I understand myFloat is a float, not an int. But the starting address of the variable myFloat is an int. Why can't you initialize int *pint to the address of myFloat?
What do you think is the type of &myFloat?
 
  • #82
Jarvis323 said:
You need to slow down and learn what the code you are writing actually means, not just what you expect it to do.
+1
 
  • #83
yungman said:
C++:
float myFloat;
int *pint = &myFloat;
I understand myFloat is a float, But the starting address of the variable myFloat is an int. Why can't you initialize int *pint to the address of myFloat?
It's because there generally aren't just plain pointers -- they are almost always pointers to some particular type. In your example, myFloat is a pointer to type float. pint is a pointer to an int. You can't do what you're trying to do without some casts, and even then, you might not get what you expect.
Here's an updated version of your example.
C++:
float myFloat = 3.75F;
int * pInt = (int *)(&myFloat);
int val = *pInt;
Note that I'm using the old-style casts.
In this code, val gets set to 0x40700000, or decimal 1081081856. These are the integer representations of the float 3.75.
 
  • Like
Likes yungman
  • #84
Jarvis323 said:
What do you think is the type of &myFloat?
Integer!, it's the address of the first byte of the variable myFloat.

It points to the first byte of the variable, who cares whether it's a float or int or anything.
 
Last edited:
  • #85
yungman said:
Integer!, it's the address of the first byte of the variable myFloat.

It points to the first byte of the variable, who cares whether it's a float or int or anything.
There's your problem. You don't know what the type is.
 
  • #86
Jarvis323 said:
There's your problem. You don't know what the type is.
Is int *pint declare the ADDRESS?

Is &myfloat giving you the address of the first byte of the variable of myfloat?

It's the address, who cares about whether the content of myfloat is a float or int. It's the address.
 
  • #87
yungman said:
Is int *pint declare the ADDRESS?
No. It's a variable that can be used to store an address to an int. Its type is (int*).
yungman said:
Is &myfloat giving you the address of the first byte of the variable of myfloat?
It's giving you a value of a particular type (int*), that holds the first byte of the variable myfloat.

In C and C++ you have formal types with precise definitions, and the compiler does type checking to make sure the types you are using match up.

yungman said:
It's the address, who cares about whether the content of myfloat is a float or int. It's the address.
See Mark's post to see why it's not the same thing, and doesn't give the same results whether it's a float or int.
 
Last edited:
  • Like
Likes yungman
  • #88
Jarvis323 said:
In C and C++ you have formal types with precise definitions, and the compiler does type checking to make sure the types you are using match up.
I am ok if you said you are NOT allow to do this, I can obey that. BUT if the book said int *pint declares an address, and the address of a float is an integer, there is a problem. That's why I post the question here.

BTW, do NOT ever take what the books said is the truth. I challenged the most famous book on Phase Lock Loop and the author offered me to send me the manuscript of the latest version. They are only human.

I just read the Gaddis book and put it in the notes with page number. You can check if I am right, this is my understanding. It is on the notes of Chapter 9 page 496.
 

Attachments

  • #89
yungman said:
I am ok if you said you are NOT allow to do this, I can observe that. BUT if the book said int *pint declares an address, and the address of a float is an integer, there is a problem.

There is no type that is called (address), or (integer) in the C++ type system. The book is not wrong. You just don't understand what a type is. What you are reading in the book is an english description of what it is, not what it's type is.
 
  • Like
Likes yungman
  • #90
Jarvis323 said:
There is no type that is called (address). And integer isn't a type in the C++ type system. The book is not wrong. You just don't understand what a type is.
Yes, it said int *pint define as address of pointer pint. int *pint initiates a pointer of address.
 
  • #91
yungman said:
Yes, it said int *pint define as address of pointer pint. int *pint initiates a pointer of address.
Right. It also has a type. The book described it, but didn't say what type it is. Where is the problem?
 
  • #92
Jarvis323 said:
Right. It also has a type. The book described it, but didn't say what type it is. Where is the problem?
You can have an address pointing to a float variable. All that means is pointing to the first byte of the float variable myFloat. The address is an integer.
 
  • #93
yungman said:
You can have an address pointing to a float variable. All that means is pointing to the first byte of the float variable myFloat. The address is an integer.
What is its type?
 
  • #94
Jarvis323 said:
What is its type?
myFloat is a float.

What is the address of the first byte of myFloat? Int or float?
 
  • #95
yungman said:
myFloat is a float.

What is the address of the first byte of myFloat? Int or float?
The type is (float*). Do you understand that?
 
  • #96
yungman said:
The address is an integer.

No, it isn't. The address is a pointer. "Pointer" and "integer" are different types in C. The fact that you, a human, can take the bits stored in a pointer and interpret them as an integer is irrelevant; C doesn't care and doesn't treat them the same way.

yungman said:
What is the address of the first byte of myFloat? Int or float?

Neither. It's a pointer. A pointer in C is a different type from either int or float.

More specifically, it's a pointer to a float, which is a different type in C from a pointer to an int.
 
  • Like
Likes Jarvis323
  • #97
PeterDonis said:
No, it isn't. The address is a pointer. "Pointer" and "integer" are different types in C. The fact that you, a human, can take the bits stored in a pointer and interpret them as an integer is irrelevant; C doesn't care and doesn't treat them the same way.
Neither. It's a pointer. A pointer in C is a different type from either int or float.

More specifically, it's a pointer to a float, which is a different type in C from a pointer to an int.
int *pint defines the address of the physical memory location. It HAS TO BE an integer. I designed plenty of real hardware with physical memory. It HAS to be integer. It cannot be a fraction. Take my word on this one. I can show you plenty of example of real schematic of address from A0 to whatever 64bits or 32 bits, it's INTEGER. This is physical hardware.
 
  • #98
yungman said:
int *pint defines the address of the physical memory location. It HAS TO BE an integer.

Sorry, but the actual workings of the C compiler trump your intuitions.

To the C compiler, an address is not an integer, it's a pointer, which is a different type from an integer. No amount of ranting by you will change that.

You can either accept this fact, or you can continue to waste the time of others here by asking questions to which you refuse to accept the correct answers.

yungman said:
I designed plenty of real hardware with physical memory.

We all understand how hardware works. But you don't understand how the C language and the C compiler work. And since you are trying to program in C, not enter hardware instructions directly into the hardware, it is knowledge about how C works that is relevant for this discussion. Knowledge that you do not have, and which you are never going to acquire if you refuse to listen to people who do have it.

yungman said:
It cannot be a fraction.

Nobody is saying it's a fraction. It's a pointer.

yungman said:
Take my word on this one.

No. The one who needs to be taking the word of others is you. Other people who know far more than you do about how the C language and the C compiler actually work are trying to help you. You need to listen to them, not demand that they listen to you.

If you are unable or unwilling to do this, your thread will end up getting closed. This one exchange has already taken up more time and energy from other posters than it should.
 
  • Like
Likes Mark44 and pbuk
  • #99
yungman said:
int *pint defines the address of the physical memory location. It HAS TO BE an integer. I designed plenty of real hardware with physical memory. It HAS to be integer. It cannot be a fraction. Take my word on this one.
As an example, a char is for storing an integer that is interpreted as an ascii2 character, its type is char.
 
  • #100
Jarvis323 said:
As an example, a char is for storing an integer that is interpreted as an ascii2 character, its type is char.

The OP's confusion is not about different ways bytes stored in memory can be interpreted. His confusion is about how the addresses of those bytes are interpreted.
 
  • Like
Likes yungman

Similar threads

Replies
7
Views
2K
Replies
6
Views
2K
Replies
5
Views
2K
Replies
75
Views
6K
Replies
9
Views
2K
Replies
6
Views
4K
Back
Top