Why does it here giving me 3 not 0? [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
create a list:
list<int> l;
auto it = l.begin();
l.emplace(it, 0);
/*it =*/ l.emplace(it, 1);
/*it =*/ l.emplace(it, 2);
here to print
for (auto it : l)
cout << it << endl; // 0 1 2
cout << "\n\n";
cout << *it << endl; // = 3
Why is *it 3 and not 0?

At this line:
auto it = l.begin();
There is nothing in the list yet, so the beginning is also the end.
std::list::emplace() inserts items before the given iterator, so this line:
l.emplace(it, 0);
Places 0 before it, ie it inserts at the end of the list.
std::list also has some of the most forgiving iterator invalidation rules, and the it iterator is not invalidated as items are inserted into the list. it continues to refer to the end of the list as new items are added to the list.
Ultimately, this line:
cout << *it << endl;
Dereferences the "end" iterator, and this is not allowed. The results are undefined, and in this case it appears to contain the value 3. Maybe if you add another item then it'll appear to contain 4, and maybe you're seeing a hidden implementation-specific detail of the list. Or maybe the computer will crash or get a bad case of the nasal demons.

Related

C++ Find & Change Value in Map [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I've scoured but not finding a solution; this is part of a homework assignment so looking more for tips/explanation than outright solution.
Problem:
I am parsing a file and extracting key elements into a map. I've declared my standard non-const map as : map<label,element>. In a second phase of the program, I am needing to locate if exists in "map" and replace its value.
I'm able to find the element, and print it, but I can't seem to get it to change. It's not a constant, so it should be editable, but maybe I'm using the wrong function?
((For reference, i is a line number (19, current value stored in map), value_i is a stored int variable I'm trying to insert into my second element (current value is 0) ))
for (auto &el : labels) {
if (el.second == i) {
el.second == value_i;
std::cout << "Label " << el.first << " value changed to: " << el.second << std::endl;
}
Output:
Label n value changed to: 19
Desired Ouput:
Label n value changed to: 0
Thanks in advance!!
you made a simple mistake which is el.second == value_i; - you didn't assign value for second, you checked if its equal value_i. If your compiler didn't give you any warning about it, I recommend setting a higher level of warnings ( you can read online on how to do it on probably every compiler), that way you won't miss such small mistakes.
If you change this line of code to:
el.second = value_i;
It will do what you desired.

C++ for loop and do-while loop of a single dimensional array gives questionable output [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am taking a course on edx.org Introduction to C++ by Microsoft. I get unwanted output when looping through a single dimensional array. The code is below.
<#include <iostream>
int main() {
int arrayName[10] = { 1,2,3,4,5,6,7,8,9,10 };
for (int i = 1; arrayName[i] <= 20; i++) {
std::cout << i << std::endl;
}
The output of this is:
1
2
3
4
5
6
7
8
9
10
11
Where does the 11 come from? And, if I make i=0, it also prints a 0. How does it print more than 10? And, when I try to change arrayName[10] to arrayName[9], I get a compiler error that there are too many initialized values:
int arrayName[10] = { 1,2,3,4,5,6,7,8,9,10 };
do {
std::cout << i << std::endl;
i++;
} while (arrayName[i] < 5);
The output is:
12
13
14
15
16
17
18
That do-while loop outputs 7 integers that I did not specify to be included in the arrayName[] array.
I don't know what I am doing wrong or what I am not understanding.
Please help. Thank you!
First, note that arrays in c++ start at index 0. So in int arrayName[3] = {10, 42, 88}; then arrayName[1] is 42, not 10. That means the last element in this array is int arrayName[2]. There is no element at index 3.
Your array only contains 10 elements (indices 0 to 9). The standard does not specify what happens when you access an element past the end of an array, anything can happen. In your case, arrayName[10] and arrayName[11] happens to give you something less than or equal to 20, and then arrayName[12] gave you something greater than 20, ending the loop. If you try it on another computer, or even at a different time, the results will vary. It might also crash (this is the best case scenario).
See this answer for more information on undefined behavior.
I finally found this: Correct way of loop through the C++ arrays, answer by https://stackoverflow.com/users/1619294/mark-garcia.
Changed my code to:
std::cout << "Looping through arrayName3 with std::array and letting the compiler determine how many objects to print:" << std::endl;
// Need to #include <array>
std::array<int, 10> arrayName3 = { 1,2,3,4,5,6,7,8,9,10 };
for (const auto& i : arrayName3) // Range-for
{
std::cout << i << std::endl;
}
The output was what I wanted:
1
2
3
4
5
6
7
8
9
10
This let's the compiler know it is deciding what to output. It would be great to know how to change this to control how many indices to loop through.

Operation on vector [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want my program to create and output 4 sets, each having 13 numeric elements.
Expected output is 1.1, 1.2, ..., 1.13, 2.13, ..., 4.13 (set and element is represented as set.element):
Set Element
1 1
1 2
...
1 13
2 1
2 2
...
2 13
...
4 13
I also want to store this data in a std::vector so that I can access and reuse it by using functions at or operator[].
My current output is 0. I want to display the output at a particular index, say output at index 30.
Code:
vector<int> storein(52);
int sortn;
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 13; j++)
{
storein.push_back(j);
cout << i + 1 << "\t" << j << endl;
}
}
// cout << storein.size();
cout << storein[30] << endl;
Live example: http://ideone.com/XcGAyX
vector<int> storein(52);
The vector now has 52 elements.
The calls to push_back add more elements to the end of the vector. When you refer to storein[30], you find one of the original 52 elements.
Try this:
vector<int> storein;
In general, when you start to use a new tool, you should try the simplest things you can do, test the results, and build up to more complex operations. This is a vital skill.

C++ it changes the value of the variable because of..? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
That is the code:
point [1][2][1] = 3;
cout << point[1][2][1] << endl;
point [1][3][0] = 4;
cout << point[1][2][1] << endl;
And that is what the console says when I run the application:
3
4
If I change to
point[1][3][0] = 5;
it says
3
5
How can I remove this annoying error? I cant continue that way.
When your variable is declared as
int point[100][100][1];
Then the valid indexes are respectively 0...99, 0...99, 0...0.
Your access to point[1][2][1] is therefore quite inappropriate. Depending on which index you make out of range, you might access an area outside the array entirely, or in a different slice of the array.
If you really want to access array elements arbitrarily, then I suggest you discard the triple-subscript notation and use:
int point[m][n][p];
int* p = &point[0][0][0];
p[x*n*p + y*p + z]
Now you are in control over row-major vs column-major access, and any computation that yields an offset less than m*n*p is valid.
Note that in your case m=n=100 and p=1, so that point[1][3][0] is p[1*100*1 + 3*1 + 0] = p[103] and also point[1][2][1] is p[1*100*1 + 2*1 + 1] = p[103]. So both really are the same location.

Understanding find and vectors C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to understand this line of code
vector<int>::iterator it = find(list_vector.begin(), list_vector.end(), 5)
where I have vector<int> list_vector; declared before hand.
What does the 5 do? What does it return? Does it return the 5 if it can find it at the beginning and end? If I wanted to make an if statement, and I wanted to find if the number 10 was in the statement (if it was, return true) how would I go about doing that?
vector<int>::iterator it = find(list_vector.begin(), list_vector.end(), 5)
std::find searches in the range defined by its first two arguments. It returns an iterator pointing to the first element that matches. If no element matches, it returns its 2nd parameter.
list_vector.begin() returns an iterator that points to the first element of list_vector.
list_vector.end() returns an iterator that points one element beyond the final element of list_vector.
5 is the target of the search. find() will look for an element that has the value 5.
If you'd like to determine if 10 is present anywhere in the vector, do this:
if(std::find(list_vector.begin(), list_vector.end(), 10) == list_vector.end())
std::cout << "No 10, bummer\n";
else
std::cout << "I found a 10!\n";
Or, if you'd like to simultaneously determine if 10 is present and determine its location:
std::vector<int>::iterator it = std::find(list_vector.begin(), list_vector.end(), 10);
if(it == list_vector.end())
std::cout << "No 10\n";
else
std::cout << "Look what I found: " << *it << "\n";