why is the sort() changing my input array? - c++

i am stuck on a problem where, after taking input of an array and sorting it and not doing any operation on it at all, the output shows a different array?
#include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t--){
int n;
cin>>n;
long long int c[n],h[n],a[n];
for(int i=0;i<n;i++){
cin>>c[i];
}
for(int i=0;i<n;i++){
cin>>h[i];
}
sort(h,h+n);
for(int i=0;i<n;i++){
a[i]=0;
}
int i=0;
int begin=(i+1)-c[i];
int end = (i+1)+c[i];
int j=begin;
while(i<n){
a[j-1]++;
j++;
if(j>end){
i++;
begin=(i+1)-c[i];
end= (i+1)+c[i];
j=begin;
}
}
sort(a,a+n);
for(int i=0;i<n;i++){
cout<<h[i]<<" ";
}
}
return 0;
}
input for h[]={8,8,8,8,8}..n=5
output h[]={10,10,9,9,8}

Here is a version of your code written in reasonably decent C++. I didn't touch the loop in the middle because I have no clue what it's doing. You're using obscure variable names and no comments and doing all kinds of bizarre things with indexes and mixing them up with user input.
Now, reading indexes from user input and using them isn't bad, though in a real program you'd want to be doing lots of bounds checking on that input to make sure people weren't feeding you bad data. But doing all that stuff with such poorly named variables with no explanation is going to leave anybody looking at it scratching their head. Don't do that.
Also, avoid the use of begin and end as variable names, especially if they hold indexes. In most cases it will confuse things terribly as begin and end are important identifiers in the standard library and always refer to iterators, which are sort of like indexes, but most definitely not indexes, adding greatly to the confusion. beginidx and endidx could be acceptable substitutes in this case.
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
using ::std::vector;
using ::std::sort;
using ::std::copy_n;
using ::std::copy;
using ::std::fill;
using ::std::istream_iterator;
using ::std::ostream_iterator;
using ::std::cin;
using ::std::cout;
int main() {
// your code goes here
using vec_el_t = long long int;
int t;
cin >> t;
while (t--) {
int const n = []() { int n; cin >> n; return n; }();
vector<vec_el_t> c{n}, h{n}, a{n};
copy_n(istream_iterator<vec_el_t>{cin}, n, c.begin());
copy_n(istream_iterator<vec_el_t>{cin}, n, h.begin());
// Suggested debugging code:
// cout << "h before sort: "
// copy(h.begin(), h.end(), ostream_iterator<vec_el_t>{cout, " "});
// cout << '\n';
sort(h.begin(), h.end());
// Suggested debugging code:
// cout << "h after sort: "
// copy(h.begin(), h.end(), ostream_iterator<vec_el_t>{cout, " "});
// cout << '\n';
fill(a.begin(), a.end(), 0);
// Weird, unexplained algorithm begins here
int i = 0;
int begin = (i + 1) - c[i];
int end = (i + 1) + c[i];
int j = begin;
while (i < n) {
a[j - 1]++;
j++;
if (j > end){
i++;
begin = (i + 1) - c[i];
end = (i + 1) + c[i];
j = begin;
}
}
// Weird unexplained algorithm ends here
sort(a.begin(), a.end());
copy(h.begin(), h.end(), ostream_iterator<vec_el_t>{cout, " "});
}
return 0;
}
Changes made... Use vector not a variable length array, which isn't valid C++ anyway and will only work in g++ and clang. Don't use explicit loops if there is an algorithm that will do the job. Try to make as many things const as you can so you can make sure that the compiler catches it if you try to change things you didn't mean to change. Avoid using std; and if you want to import names from ::std import exactly the ones you need. Don't use compiler or library implementation specific header files and use the ones from the standard instead (i.e. no bits/stdc++.h).
As for your problem, I have no idea. I suspect that the index manipulation combined with looping isn't doing what you expect. If you print out the arrays before and after sorting, you will discover that sort only alters order, and not content.
As a general rule, always suspect your own code first and make absolutely sure it's correct. And if you really think it's the library code, prove it beyond a shadow of a doubt before coming here to ask why the library isn't doing what it says it does.
The complicated code I didn't touch looks rife with opportunities for out-of-bounds access, and that results in undefined behavior, which means your program might do absolutely anything in that case. You might change uses of operator [] with calls to the at function (one of the many perks of using vector) instead. That way, attempts at out-of-bounds access will throw an exception.

Within these lines you are accessing a outside its limits:
int i=0;
int begin=(i+1)-c[i]; // begin = 1 - c[0]; <<-- this could be arbitrarily small!
int end = (i+1)+c[i]; // unrelated
int j=begin; // also equal to 1-c[0]
while(i<n){
a[j-1]++; // increment a[-c[0]] which is UB unless c[0]==0
This means undefined behavior (UB), i.e., it could do nothing, it could segfault, or (what apparently happened in your case) access elements of an adjacent data structure.

Related

Need explanation of this, what actually is going on in this line?

I am converting some C++ code into python. but I am not sure what exactly this line do.
vector<double>().swap(prev);
I compiled a simple program to see what it actually do, I found that it resizes the vector "prev" to 0.
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> ax;
ax.reserve(10);
for(int i=99; i<110; ++i){
ax.push_back(i);
}
for(int i=0; i<ax.size(); ++i){
std::cout << ax[i] << ' ';
}
vector<int>().swap(ax);
cout<<"\nAfter space \n";
cout<<"size is "<<ax.size();
for(int i=0; i<ax.size(); ++i){
std::cout << ax[i];
}
}
It's the result of the programmer deciding that, for some reason,
vector<int>().swap(ax);
is clearer than
ax.clear();
(The former exchanges the initially empty anonymous temporary vector<int>() with ax).
Somewhat less cyncially perhaps, the swap method might reset the capacity of the vector, whereas clear() never does. But it's still an odd choice: if you want the capacity to be reset then use
ax.clear();
ax.shrink_to_fit();
but even that is not guaranteed to reset the capacity; it's up to the implementation to decide.

creating mxn 2D array in c++ without using any external library

I am a beginner to C++ syntax. Now, I need to create an mxn 2D array in C++ to use it in another project. I have looked at other answers which involve using tools like vector, etc. Many tools are not working on my Visual Studio 15 i.e. for vector I can not define with std::vector without a message like vector is not in std. So, I have wrote the following code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int i; int j; int row[5][10] = {};
for (int j = 0; j < 10;)
for (int i = 0; i < 5;)
{
row[i][j] = 500;
int printf(row[i][j]);
i++;
j++;
cout << "Array:" << row[i][j] << endl;
}
return 0;
}
Surely, this is not the correct syntax. So the output is beyond my expectation. I want to create an m*n array with all the elements being the same integer; 500 in this case. That is, if m=3, n=2, I should get
500 500 500
500 500 500
There's a couple things wrong with your current code.
The first for loop is missing curly brackets
You're redefining int i and int j in your for loop. Not a complilation issue but still an issue.
You're using printf incorrectly. printf is used to output strings to the console. The correct line would be printf("%d", row[i][j]);
If you want to use a vector, you have to include it using #include <vector>. You can use a vector very similar to an array, but you don't have to worry about size.
You seem to be learning. So, I did minimal correctios to make it work. I suggest you to make modifications as per your needs.
#include <iostream>
using namespace std;
int main()
{
int row[5][10] = {};
for (int j = 0; j < 10; j++) {
for (int i = 0; i < 5; i++) {
row[i][j] = 500;
cout << row[i][j] << " ";
}
cout << endl;
}
return 0;
}
Care and feeding of std::vector using OP's program as an example.
#include <iostream>
#include <vector> // needed to get the code that makes the vector work
int main()
{
int m, n; // declare m and n to hold the dimensions of the vector
if (std::cin >> m >> n) // get m and n from user
{ // m and n are good we can continue. Well sort of good. The user could
// type insane numbers that will explode the vector, but at least they
// are numbers.
// Always test ALL user input before you use it. Users are malicious
// and incompetent <expletive delteted>s, so never trust them.
// That said, input validation is a long topic and out of scope for this
// answer, so I'm going to let trapping bad numbers pass in the interests
// of keeping it simple
// declare row as a vector of vectors
std::vector<std::vector<int>> row(m, std::vector<int> (n, 500));
// breaking this down:
// std::vector<std::vector<int>> row
// row is a vector of vectors of ints
// row(m, std::vector<int> (n, 500));
// row's outer vector is m std::vector<int>s constructed with
// n ints all set to 500
for (int j = 0; j < n; j++) // note: j++ has been moved here. This is
// exactly what the third part of a for
// statement is for. Less surprises for
// everyone this way
// note to purists. I'm ignoring the possible advantages of ++j because
// explaining them would muddy the answer.
// Another note: This will output the transverse of row because of the
// ordering of i and j;
{
for (int i = 0; i < m; i++) // ditto I++ here
{
// there is no need to assign anything here. The vector did
// it for us
std::cout << " " << row[i][j]; // moved the line ending so that
// the line isn't ended with
// every column
}
std::cout << '\n'; // end the line on the end of a row
// Note: I also changed the type of line ending. endl ends the line
// AND writes the contents of the output stream to whatever media
// the stream represents (in this case the console) rather than
// buffering the stream and writing at a more opportune time. Too
// much endl can be a performance killer, so use it sparingly and
// almost certainly not in a loop
}
std::cout << std::endl; // ending the line again to demonstrate a better
// placement of endl. The stream is only forced
// to flush once, right at the end of the
// program
// even this may be redundant as the stream will
// flush when the program exits, assuming the
// program does not crash on exit.
}
else
{ // let the use know the input was not accepted. Prompt feedback is good
// otherwise the user may assume everything worked, or in the case of a
// long program, assume that it crashed or is misbehaving and terminate
// the program.
std::cout << "Bad input. Program exiting" << std::endl;
}
return 0;
}
One performance note a vector of vectors does not provide one long block of memory. It provides M+1 blocks of memory that may be anywhere in storage. Normally when a modern CPU reads a value from memory, it also reads values around it off the assumption that if you want the item at location X, you'll probably want the value at location X+1 shortly after. This allows the CPU to load up, "cache", many values at once. This doesn't work if you have to jump around through memory. This means the CPU may find itself spending more time retrieving parts of a vector of vectors than it does processing a vector of vectors. The typical solution is to fake a 2D data structure with a 1D structure and perform the 2D to 1D mapping yourself.
So:
std::vector<int> row(m*n, 500);
Much nicer looking, yes? Access looks a bit uglier, though
std::cout << " " << row[i * n + j];
Fun thing is, the work done behind the scenes converting row[j][i] to a memory address is almost identical to row[j*n+i] so even though you show more work, it doesn't take any longer. Add to this the benefits you get from the CPU successfully predicting and reading ahead and your program is often vastly faster.

Why do I get random numbers after the input?

I'm trying to take in some input and find the number of a certain character in a string. I keep getting a weird answer when I try to take in the actual string. Why is this happening?
I'm using cout to find why I'm getting such weird numbers and it appears to be a problem with the input.
Note - This is my attempted solution to Codeforces Problem 462 B. I'm attempting to just find the number of a certain letter in the input. My friend is attempting a bubble sort method.
Input:
6 4
YJSNPI
Expected Output:
YJSNPI
4
Actual Output:
YJSNPI
1699623981
Code:
#include <iostream>
#include <string>
#include <vector>
#include <istream>
using namespace std;
int main()
{
int n, k, counting;
cin >> n >>k;
char trash;
cin.get(trash);
vector<string> cards;
string theline, name;
cin >> theline;
cout << theline << "\n";
for (int i = 0; i < n; i++){
name = theline[i];
cards.push_back(name);
}
for (int i = 0; i < n; i++){
if (cards[i] == cards[k-1]){
counting++;
}
}
int tmp = 0;
if (cards.size() != k){
tmp = k - counting;
}
counting *= k;
counting += tmp;
cout << counting;
return 0;
}
Local variables are not automatically initialized to 0. If you try to use the value of a local variable before assigning it, you get undefined behavior. You're incrementing counting without ever initializing it. Change to:
int n, k, counting = 0;
The issue is that the variable "counting" is never initialized - handy link
Basically, "counting" has some garbage value from memory after you declare it with
int counting;
Then, the first operation performed is
counting++;
And the garbage value is saved.
THE FIX:
Change
int counting;
to
int counting = 0;
NOTE: n and k are not helpful variable names. It would make understanding the code a lot easier if they had real names, but oh well.
ADDITIONALLY:
As chris mentioned above, make the compiler work for you. See comment below for good compiler flags. Don't ignore warnings!
Can't really understand what you are doing here. But I can see where you are going wrong.
int n, k, counting;
counting is uninitialized try
int n, k, counting = 0;
I get answer of (1*4 + 4 - 1) = 7 not the 4 you are expecting.
This code will always result in counting = 1, given that k is within range.
for (int i = 0; i < n; i++){
if (cards[i] == cards[k-1]){
counting++;
}
}
https://ideone.com/7Hk3ix

Why is this code showing segmentation error on codechef?

Please i am stuck at this question for half an hour and can't find why the error comes?
Problem code : test
Life, Universe and Everything
#include<iostream>
using namespace std;
int main()
{
int a[20],i;
cin>>a[0];
for(i=1;a[i-1]!=42;i++)
{
cout<<a[i]<<"\n";
cin>>a[i];
}
return(0);
}
Your code tries to access non-existing array elements, which causes segfault. You should stop your loop before the array index gets larger than the length of the array minus 1:
int a[20];
for (i = 1; i < 20 && a[i - 1] != 42; i++)
{
// ...
}
Apart from limit problem, your printing elements without initializing them
//for i = 1, a[i] is uninitialized
cout<<a[i]<<"\n";
On accessing a local variable (like this), you're likely to get garbage value.
This might be better substitute for what you are trying to do:
int a[20],i;
for(i=0;i < 20;i++)
{
cin>>a[i];
if (a[i] == 42)
break;
cout<<a[i]<<"\n";
}
You are trying to print the uninitialized data...
#include<iostream>
using namespace std;
int main()
{
int a[20],i;
cin>>a[0]; // a[0] uninitialized
for(i=1;a[i-1]!=42;i++)
{
cout<<a[i]<<"\n";
cin>>a[i];
}
return(0);
}
In the for loop get the data first and then print it.Your array size is 20 but you are trying to write upto 42.
You use array values before initializing them. C++ doesn't initialize non-static arrays for you unless you tell it to, so $DEITY knows what's in there. And technically, whatever's in there could cause an exception...or any number of other things. (For ints, on an x86 machine, that's actually highly unlikely. But elsewhere, it's possible.)
The user can enter more than 20 numbers. That's really just a special case of the more general problem, though: You allow unknown number of entries, but aren't able to accept them all without crashing.
If you don't know beforehand how many objects there will be, use a vector.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::vector<int> a;
int entry;
cin>>entry;
// Oh, yeah. This. You really, *really* want to check `cin`.
// Otherwise, if the user decided to type "i like cheese", you'd loop
// forever getting zeros while cin tried to parse a number.
// With the array, that'd typically cause a segfault near instantly.
// With a vector, it'll just eat up all your CPU and memory. :P
while (cin && entry != 42) {
a.push_back(entry);
cout << entry << "\n";
cin >> entry;
}
return 0;
}

Reducing time in the following code

I gave this solution at the codechef for the problem code : FCTRL.
I saw the compile time of others people using the same the language c ( i am using c++ gcc 4.8.1) is somewhat less,
mine is 0.46s while their is 0.23
Can somebody help me in reducing the time if possible?
#include<iostream>
using namespace std;
int main()
{
long int t,i,temp;
cin>>t;
long int n[t],a[t];
for(i=0;i<t;i++)
{
temp=1;
a[i]=0;
cin>>n[i];
while(temp)
{
temp=n[i]/5;
a[i]+=temp;
n[i]=n[i]/5;
}
}
for(i=0;i<t;i++)
cout<<a[i]<<"\n";
return(0);
}
From your description, as you are using c++ and they are using c, it might be due to how the compiler handles each instruction.
Also you may try replacing
temp=n[i]/5;
a[i]+=temp;
n[i]=n[i]/5;
By
temp=n[i]/5;
a[i]+=temp;
n[i]=temp; //why compute the value again
And see if some time reduces or not
You worst offense to C++ is using Variadic-Length arrays, those are non-standards.
And in fact, it turns out you absolutely do not need them. This problem can be solved on a line-per-line basis so using arrays to hold the input and output is useless.
Here is your program, simplified. I also noted that temp was useless within the loop (though it was likely optimized out anyway, it polluted the code).
#include <iostream>
int main()
{
size_t number = 0;
std::cin >> number;
for(size_t i = 0 ; i < number; ++i)
{
size_t a = 0, n = 0;
std::cin >> n;
while (n)
{
n /= 5;
a += n;
}
std::cout << a << '\n';
}
}
Is it possible to do better ? Oh yes! The main issues here is that the C++ streams are none too fast so you may get a good boost by switching to the C reading methods... however they are not as nice (and safe).