Debug assertion failed with list - c++

Hello everybody can you help me?
the problem is that when a person enters a element from list he can insert before this element elements from another list, but I constantly knock out mistakes. Maybe someone will help?
It looks like:
3 6 7 9
user enters 6
he can create another list like 8 7 5
and output is 3 8 7 5 6 7 9
The error
#include <iostream>
#include <list>
#include <algorithm>
#include <iterator>
int main()
{
int size
int size1;
int el1;
int znach=0;
cout << "Enter size: " << endl;
cin >> size;
list<int>lis;
list<int>lis1;
list <int> ::iterator it;
int s = lis.size() / 2;
auto it1 = lis.begin();
advance(it1, s);
for (int i = 0; i <size; i++)
{
cout << "Enter " << i << " element: ";
cin >> t;
lis.push_back(t);
}
cout << "Enter element: " << endl;
cin >> el1;
for (it = lis.begin(); it != lis.end(); it++)
{
if (*it = el1)
{
znach++;
}
}
if (znach == 0)
{
cout << "There is no element;" << endl;
}
else
{
cout << "Enter size of new vector: " << endl;
cin >> size1;
for (int i = 0; i < size1; i++)
{
int t1;
cout << "Enter " << i << " element: ";
cin >> t1;
lis1.push_back(t1);
}
auto it2 = lis.begin();
while (*it2 != el1)
{
it2++;
}
--it2;
lis.splice(it2, lis1);
}
for (it = lis.begin(); it != lis.end(); it++)
{
cout << *it<<" ";
}
}

I don't know what your code is doing, and maybe there are other problems. However, the runtime error you get is caused by
auto it2 = lis.begin();
while (*it2 != el1)
{
it2++;
}
--it2;
When *lis.begin() == el1 then you never increment it2 and then decrement it, but you cannot decrement the begin iterator. Usually thats just undefined, but as you compiled a debug build you got an assertion fired up that tells you what went wrong.

Related

Why is my code not working properly? Is there something in STL-list which I am forgetting?

This is my code:
#include <iostream>
#include <list>
using namespace std;
template <class T>
void display(list<T> l){
list<int>::iterator i;
for (i = l.begin(); i != l.end(); i++)
{
cout << *i << " ";
}
}
void enter(list<int> l){
list<int>::iterator i;
int index = 1;
for (i = l.begin(); i != l.end(); i++, index++)
{
// cout << "check" << endl;
cout << "Enter element at index " << index << endl;
cin >> *i;
}
}
int main(){
list<int> l;
display(l);
cout << endl;
l.push_front(1);
l.push_front(2);
l.push_front(3);
l.push_front(4);
l.push_front(5);
list<int> l2(3);
enter(l2);
display(l2);
cout << "EXE";
return 0;
}
The output of the following program is:
Enter element at index 1
1
Enter element at index 2
2
Enter element at index 3
3
0 0 0 EXE
Required Output:
Enter element at index 1
1
Enter element at index 2
2
Enter element at index 3
3
1 2 3 EXE
The issue is that you pass the list by value in enter. When you update the list with cin >> *i, you are updating a copy of l2 instead of the l2 declared in main().
If you would like to update the list you will need to pass by reference instead.
void enter(list<int>& l){
list<int>::iterator i;
int index = 1;
for (i = l.begin(); i != l.end(); i++, index++)
{
// cout << "check" << endl;
cout << "Enter element at index " << index << endl;
cin >> *i;
}
}

C++:cannot seek vector iterator before begin

I was doing a uva problem uva 10935 throwing cards away, and my code is as follows. when i ran it, it said An unhandled exception was raised: read access conflict, and it also shows "cannot seek vector iterator before begin", i don't know where is the problem in my code:
#include<vector>
#include<iostream>
using namespace std;
int n;
vector<int> out;
int main() {
freopen("data.txt", "r", stdin);
while (scanf("%d", &n) == 1 && n) {
vector<int> cards;
for (int i = 1; i <= n; i++)cards.push_back(i);
vector<int>::iterator it = cards.begin();
vector<int>::iterator end = cards.end();
while (it != (end-1)) {
out.push_back(*it);
it++;
cards.push_back(*it);
it++;
end++;
}
cout << "Discarded cards: ";
for (int j = 0; j < out.size(); j++) {
if(j!=(out.size()-1))cout << out[j] << ", ";
else cout << out[j] << endl;
}
cout << "Remaining card: " << *it << endl;
}
return 0;
}
The problem here remains in the while() loop, where you are pushing new element in the vector while holding it's old "end" address as terminal reference.
When a vector pushes a new element, it may need to reallocate it's whole array to a new location. In that case, the "end" reference that you are holding will become obsolete as you are increasing it linearly, but the whole vector after that push may have shifted somewhere else.
I added some debug lines in your code, so you can see how this happens. Just run the code with an input value of 4. And you will see the "end" value probably will not relate with the vector's reallocated address anymore (if reallocation happens, it basically depends on the system to decide).
#include<vector>
#include<iostream>
using namespace std;
int n;
vector<int> out;
void printVectorElementAddresses(vector<int> &v){
cout<<"==== Vector Element Addresses ====\n";
for(auto itr = v.begin(); itr != v.end(); itr++)
{
cout<<&(*itr);
if(itr == v.end()-1){
cout<<endl;
}
else{
cout<<" ";
}
}
cout<<endl;
}
void printIteratorAddressWithTag(char* tag, vector<int> :: iterator & it, bool printNewLine){
cout<<tag<<&*it<<"; ";
if(printNewLine){
cout<<endl;
}
}
int main() {
// freopen("data.txt", "r", stdin);
while (scanf("%d", &n) == 1 && n) {
vector<int> cards;
for (int i = 1; i <= n; i++)cards.push_back(i);
vector<int>::iterator it = cards.begin();
vector<int>::iterator end = cards.end();
//print vector addresses after initial pushes are done
printVectorElementAddresses(cards);
while (it != (end-1)) {
printIteratorAddressWithTag("it initial = ", it, false);
out.push_back(*it);
it++;
printIteratorAddressWithTag("it after first increment = ", it, false);
cards.push_back(*it);
it++;
printIteratorAddressWithTag("it after second increment = ", it, true);
printIteratorAddressWithTag("end initially in loop = ", end, false);
end++;
printIteratorAddressWithTag("end after increment = ", end, true);
cout<<"Vector Addresses after a new push"<<endl;
printVectorElementAddresses(cards);
}
cout << "Discarded cards: ";
for (int j = 0; j < out.size(); j++) {
if(j!=(out.size()-1))cout << out[j] << ", ";
else cout << out[j] << endl;
}
cout << "Remaining card: " << *it << endl;
}
return 0;
}
Just change the logic in your while loop to keep track of the old "end" reference after the push happens. And if the other logic are fine, it should work.
I think there is a problem with end++, and others iterators.
If the vector cards grows, its memory location may be changed, and end++ will be pointing to an invalide position. Similar happens with it++.
I propose you to use lists instead:
#include<bits/stdc++.h>
using namespace std;
int n;
int main() {
//freopen("a.in", "r", stdin);
while (scanf("%d", &n) == 1 && n) {
list<int> out;
list<int> cards;
for (int i = 1; i <= n; i++)
cards.push_back(i);
list<int>::iterator it = cards.begin();
list<int>::iterator end = cards.end();
end--;
while (it != (end)) {
out.push_back(*it);
it++;
cards.push_back(*it);
it++;
end++;
}
cout << "Discarded cards: ";
list<int>::iterator it2 = out.begin();
for (int j = 0; j < out.size(); j++, it2++) {
if(j !=(out.size()-1))
cout << *it2 << ", ";
else
cout << *it2 << endl;
}
cout << "Remaining card: " << *it << endl;
}
return 0;
}
NOTE: I haven't read the UVA problem.

Using an Array[10] and incrementing it with a While loop using modulo 10 to Pair User inputs together

#include <iostream>
using namespace std;
int main()
{
long int number;
int digits;
cout << "Enter Number: ";
cin >> number;
int counter[10] = { 0,0,0,0,0,0,0,0,0,0 };
while (number != 0) {
digits = number % 10;
counter[digits] = counter[digits] + 1;
number = number / 10;
}
for (int i = 0; i<10; i++) {
if (counter[i] != 0) {
cout << i << ": " << counter[i] << endl;
}
}
return 0;
system("pause");
}
I'm having an issue with my code that when I run it and enter a Number nothing really happens. It is supposed to run something like 1234556789 and the output should look like
1 : 9
2 : 8
3 : 7
4 : 6
5 : 5
I know sometimes if there isn't a system pause this happens where it runs part of the code and just ends, but I'm not sure whats wrong here.
#include <iostream>
using namespace std;
int main()
{
long int number;
int digits;
cout << "Enter Number: ";
cin >> number;
int counter[10]={0},a=0;
while (number != 0) {
digits = number % 10;
counter[a] = digits; //made changes to this line
number = number / 10;
++a;
}
for (int i = 0; i<10; i++) {
if (counter[i] != 0) {
cout << i << ": " << counter[i] << endl;
}
}
return 0;
}
All you are doing right now is printing how many digits there are of each number 0-9 in the number. If you want to pair elements together, then you can use std::vector and iterators. The number of digits in your input can be either even or odd and you would have to account for both cases.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
long int number;
cout << "Enter Number: ";
cin >> number;
vector<int> digits;
if (number == 0)
{
digits.push_back(number);
}
while (number != 0)
{
digits.push_back(number % 10);
number /= 10;
}
auto it_begin = digits.begin();
auto it_end = digits.end() - 1;
if (digits.size() % 2 == 1)
{
for (; it_end != it_begin; ++it_begin, --it_end)
{
cout << *it_end << ": " << *it_begin << endl;
}
cout << *it_end << endl;
}
else
{
for (; it_begin < it_end; ++it_begin, --it_end)
{
cout << *it_end << ": " << *it_begin << endl;
}
}
}
With number = 1234556789, the output is:
1: 9
2: 8
3: 7
4: 6
5: 5
If you want first 10 no. Only use this code
include using namespace std;int main() {long int number;cout << "Enter Number: ";cin >> number;for (int i = 1; i<=10; i++) {cout << i << ": "<

Why am I getting a segmentation fault in this iterator?

I'm writing a program that should look through a graph and calculate the minimum number of edges that need to be deleted to leave a forest where each connected group has an even number of vertices. I know how to solve the problem, but when I try and iterate through a list I get a segmentation fault and can't figure out why.
#include <cmath>
#include <cstdio>
#include <list>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int N;
cin >> N;
int M;
cin >> M;
// matrix of adjacency list to hold node values
vector<list<int> > adjList(N, list<int>());
// find the number of children nodes each node has
int ui, vi;
for (int i = 0; i < M; i++) {
cin >> ui;
cin >> vi;
ui--;
vi--;
//cout << ui << " " << vi << endl;
adjList[ui].push_back(vi);
adjList[vi].push_back(ui);
//cout << "list length: " << adjList[ui].size() << endl;
}
//cout << "after for loop" << endl;
// count the number of nodes with even numbers of children
for (int i = 0; i <= M; i++) {
cout << i << "-> ";
for (list<int>::iterator it = adjList[i].begin(); it != adjList[i].end(); it++) {
cout << *it << " ";
}
cout << endl;
}
int edgesRemoved = 0;
for (int i = 0; i <= M; i++) {
for (list<int>::iterator it = adjList[i].begin(); it != adjList[i].end(); ++it) {
int j = *it;
if (adjList[j].size() % 2 == 1) {
// delete vertex from current list
cout << "test" << endl;
adjList[i].erase(it);
// delete vertex on the other list
cout << "test" << endl;
cout << j << endl;
cout << *adjList[j].begin() << endl;
for (list<int>::iterator it2 = adjList[j].begin(); it2 != adjList[j].end(); ++it2) {
cout << *it2 << " ";
if (i == *it2) {
adjList[j].erase(it2);
}
}
edgesRemoved++;
}
}
}
cout << edgesRemoved << endl;
return 0;
}
After using cout statements to debug the program I figured out that the problem is here:
for (int i = 0; i <= M; i++) {
for (list<int>::iterator it = adjList[i].begin(); it != adjList[i].end(); ++it) {
int j = *it;
if (adjList[j].size() % 2 == 1) {
// delete vertex from current list
cout << "test" << endl;
adjList[i].erase(it);
// RIGHT UNDER HERE
// vvvvvvvvvv
for (list<int>::iterator it2 = adjList[j].begin(); it2 != adjList[j].end(); ++it2) {
cout << *it2 << " ";
if (i == *it2) {
adjList[j].erase(it2);
}
}
edgesRemoved++;
}
}
}
I get a segmentation fault after the program creates an iterator that is meant to go through another list in the vector. I don't understand why though, the syntax is the same as the first for loop with another iterator going through the first list.
Here is an example of what happens after I type in the input of the digits that represent a tree, the program then prints the adjacency matrix and goes on to the actual calculation (this part works fine, it's the end result during calculation):
10 9
2 1
3 1
4 3
5 2
6 1
7 2
8 6
9 8
10 8
0-> 1 2 5
1-> 0 4 6
2-> 0 3
3-> 2
4-> 1
5-> 0 7
6-> 1
7-> 5 8 9
8-> 7
9-> 7
test
test
1
0
Segmentation fault
Erasing the item under the iterator invalidates the iterator; using it further results in undefined behavior, so anything could happen. The usual idiom for this sort of thing is:
std::list<int>::iterator it = adjList[i].begin();
while ( it != adjList[i].end() ) {
if ( *it == i ) {
it = adjList[j].erase( it );
} else {
++ it;
}
}
The erase function returns an iterator to the element immediately following the one which was removed.
This is valid for all sequence types, not just std::list.
You must not delete the current item in a list (the thing the iterator is pointing to) while you are iterating over it. You could do something like this:
adjList[j].erase(it2++);
However, afaik, it is considered best practice to neither shrink nor expand a list while iterating.

I want to output the unique item from specific c++ array

I have created a function to count the duplicate items in array .
And everything is fine . but I want to output the unique items only , and this is my problem .
My function:
void RepeatedCounter(int n){
int i, j, temp, count= 0;
int *Numbers = new int[n];
for(i=0;i<n;i++){
cout << "Enter the number (" << i+1 << "): ";
cin >> *(Numbers+i);
}
cout << "---------------------\n";
for(i=0;i<n;i++){
temp = *(Numbers+i);
for(j=0;j<n;j++){
if(temp == *(Numbers+j)){
++count;
}
}
if(*(Numbers+i+1) != temp)
cout << *(Numbers+i) << "= " << count << endl;
count= 0;
}
delete []Numbers;
}
Main function:
int Num_Of_Digits= 0;
cout << "How many numbers: ";
cin >> Num_Of_Digits;
RepeatedCounter(Num_Of_Digits);
Example:
Inputs
1
5
3
5
1
Wrong result (current output)
1= 2
5= 2
3= 1
5= 2
1= 2
What I want
1= 2
5= 2
3= 1
First of: read the user data into a proper dynamic container like a vector:
std::vector<int> v;
v.reserve(100);
while (true)
{
int n;
std::cout << "Enter the number: ";
if (!(std::cin >> n)) { break; }
v.push_back(n);
}
Second, make a histogram using a map:
std::map<int, unsigned int> histogram;
for (int i : v) { ++histogram[i]; }
Now output the count:
for (auto const & p : histogram)
{
std::cout << "The number " << p->first
<< " appears " << p->second << " times.\n";
}
This has been done for you.
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
int repeated_counter(int n){
std::vector<int> vec;
std::vector<int> uniques;
int t;
for(int i=0; i!=n; ++i)
{
std::cin >> t;
vec.push_back(t);
}
std::sort(vec.begin(), vec.end());
std::unique_copy(vec.begin(), vec.end(),
std::back_inserter(uniques));
for(std::vector<int>::iterator it=uniques.begin();
it!=uniques.end();
++it)
{
std::cout << *it << "="
<< std::count(vec.begin(), vec.end(), *it) << "\n";
}
return 0;
}
please refrain from newing memory like you have done it is worse in every way to using a vector.
http://www.sgi.com/tech/stl/unique_copy.html
http://en.cppreference.com/w/cpp/container/vector
Try this,
for(i=0;i<n;i++){
count= 0;
temp = *(Numbers+i);
bool found = false;
for(j=0;j<n;j++){
if(temp == *(Numbers+j)){
++count;
}
}
for(j=i+1;j<n;j++) {
if(temp == *(Numbers+j)){
found = true;
}
}
if(found) continue;
if(*(Numbers+i+1) != temp)
cout << *(Numbers+i) << "= " << count << endl;
}
The problem is you are only checking against the next number in the list.
if(*(Numbers+i+1) != temp)
cout << *(Numbers+i) << "= " << count << endl;
What you should do is loop over the front on the list (until you get to the number you're on) and check to see if any of those numbers are the same as your current number and only print out if they aren't. You could also check the number before you started the count and not do it if the number has been done already.