cant use begin() for array in c++ - c++

I am using g++ 7.1.0, yet using begin() with array as an argument throws an error. My code is
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n];
for(int i = 0; i < n; i++) {
cin>>a[i];
}
sort(begin(a), end(a));
return 0;
}
It says
no matching function for call to 'begin(int [n])'

int a[n]; is invalid statement in C++. C++ doesn't allow variable length array. It is allowed only in C since C99 standard. If you need dynamic array, you should be using std::vector 99% of the time in C++.
You can do this:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main() {
std::cout<<"Enter size of array\n";
int size;
std::cin>>size;
std::vector<int> v(size);
std::cout<<"Enter "<<size<< " elements\n";
for(size_t i=0;i<v.size();++i)
std::cin>>v[i];
std::sort(v.begin(),v.end());
std::cout<<"Sorted elements are: \n";
for(const auto& i : v)
std::cout<<i<<' ';
}
See live demo here.

#include <iterator>
<algorithm> is the wrong header for begin(), end(), and, well, all the iteration functions.
Also, for the iteration functions to work, the array must be sized with a compile-time constant, so, int a[10]; works, but int a[n]; does not.

you can do this:-
#include <algorithm>
int main(){
int arr[2000];
int n = sizeof(arr)/sizeof(arr[0]);
std::sort(arr, arr+n);
}

if you are using array instead of vector then use
sort(a,a+n);

Related

How to declare a <vector> object and use push_back inside a class?

I'm trying to build a class named "Tombola" which should contain as private variable an empty vector. This should be filled at runtime through the class member Tombola.estrai(), which generates a random number and insert it inside the vector named "order" by the method order.push_back(number). This is the class definition in the tombola.h header:
#ifndef TOMBOLA_H
#define TOMBOLA_H
#include <cstdlib>
#include <vector>
using namespace std;
class Tombola {
private:
bool on_off[90];
int tabellone[9][10];
int x_max = 9;
int y_max = 10;
vector<int> order;
public:
Tombola();
~Tombola();
void nuovo();
int estrai();
bool completato();
void stampa();
void stampa_tab();
};
#endif
And this is the implementation of constructor/destructor and Tombola::estrai() inside tombola.cc:
#include "tombola.h"
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <vector>
#include <iostream>
using namespace std;
Tombola::Tombola () {
vector<int> ord;
order = ord;
int z=1;
for(int i=0;i<90;i++) {
on_off[i] = false;
}
for(int j=0;j<=x_max;j++) {
for (int k=0;k<=y_max;k++) {
tabellone[j][k] = z;
z++;
}
}
}
Tombola::~Tombola() {
cout << "Tombola is destroyed" << endl;
}
int Tombola::estrai() {
srand(time(NULL));
int estrazione = int(ceil(rand()/double(RAND_MAX)*90));
on_off[estrazione]==true;
order.push_back(estrazione);
return order.back();
}
and this is the call to the method in the main.cpp file:
#include "tombola.h"
#include <cstdlib>
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
int main () {
Tombola natale;
cout << natale.estrai();
}
When I compile the program everything goes fine, but when I execute the main I get a segmentation fault error which seems to be due to some sort of allocation error when trying to store the item inside the order vector, as reported by the debugger. Could someone explain to me how to solve the error and why the error occours? Thank you.
The reason of segmentation fault is in the constructor. You have to change for(int j=0;j<=x_max;j++) to for(int j=0;j<x_max;j++) in order not to cross the bounds of the array.
for(int j=0;j<x_max;j++) {
for (int k=0;k<y_max;k++) {
tabellone[j][k] = z;
z++;
}
}
However, there are also some minor issues in the code that are worth being mentioned
declaring default-initialized ord vector and assigning it to order is pointless because order is already default-initialized.(See member initializer list for more information).
using namespace std; in a header file is a terrible idea, because if you had a large codebase, and had multiple source files where you want to include that header, everywhere the using statement will be applied, which probably is not desired.

How to declare an array initialize with an variable in C++

I know this sound easy to you guys but I think this may be different
Here is my simple code in which i am getting error in declaring Array
#include<iostream>
using namespace std;
int top=-1,capacity=2;
int arr[capacity];
main(){
}//main
A fixed length array needs a compile-time constant to declare its size. You need to declare capacity as const or constexpr in order to use it in an array declaration, eg:
#include <iostream>
using namespace std;
int top = -1;
const int capacity = 2;
int arr[capacity];
main(){
}
If you want to define the capacity at runtime then you need to use a dynamic array, like std::vector, eg:
#include <iostream>
#include <vector>
using namespace std;
int top = -1, capacity;
vector<int> arr;
main(){
capacity = ...;
arr.resize(capacity);
}

Xcode C++ Vectors: Implicit instantiation of undefined template

I ran this code on a different IDE and it was successful. For some reason I get the above error message on Xcode. I assume I'm missing a header of some kind, but I'm not sure which one.
#include <iostream>
#include <limits>
#include <string>
#include <vector>
int main() {
vector<string> listRestaurants; // error: Implicit instantiation of undefined template
return 0;
}
Xcode 10.2.1 was showing me the error
Implicit instantiation of undefined template 'std::__1::vector<std::__1::basic_string<char>, std::__1::allocator<std::__1::basic_string<char> > >'.
#include <iostream>
#include <vector>
int main(int argc, const char * argv[]) {
std::vector<std::string> listRestaurants;
....
return 0;
}
Fixed my issue.
If adding std:: is not the issue for you, then check if you have #include <vector>. That fixed the issue for me.
Didn't realize that #include <vector> is required. I thought it was part of standard library template; I ran this code in VSCODE IDE and it worked fine for me
#include <iostream>
#include <vector>
using namespace std;
int main()
{
uint_least8_t i; // trying to be conscious of the size of the int
vector<int> vect;
for(i = 0; i < 5; ++i)
{
vect.push_back(i);
}
for(auto i : vect)
{
cout << i << endl;
}
return 0;
}
From the comments:
The std namespace houses both of those templates. Change vector to std::vector, and string to std::string. – WhozCraig
the vector and string were placed in the namespace std
using namespace std;

C++ Unordered Map

I have a program in which I am using an iterator to get access to a value of a map entry .
#include <iostream>
#include <cstdio>
#include <unordered_map>
#include <utility>
#include <algorithm>
using namespace std;
int main()
{
int a[]={1,2,4,7,9,3,3,55,66,88,11};
int k = 58;
unordered_map<int,int> c;
int i=0;
for(auto x: a)
{
c.insert(make_pair(x,i));
i++;
}
for(auto x: c)
{
if(c.count(k-x.first)==1) printf("%d %d\n",x.second,(c.find(k-x))->second);
}
}
In the line:
if(c.count(k-x.first)==1) printf("%d %d\n",x.second,(c.find(k-x))->second);
I am getting errors especially in c.find()->second. I think it is the way to access elements from the iterator. What is wrong?
You cannot say
c.find(k-x)
Because k is an int and x is a std::pair<int, int>. Do you mean one of these two?
c.find(k - x.first)
Or
c.find(k - x.second)
As a side note, it is generally unsafe to directly derefernce the returned iterator from find because if find returns .end() (as in, it didn't find an element with that key) then you've got a problem.

std::max_element compile error, C++

Please see the following 2 examples:
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
int n;
std::cin>>n;
std::vector<int> V(n);
// some initialization here
int max = *max_element(&V[0], &V[0]+n);
}
This gives the following compiling error:
error C3861: 'max_element': identifier not found
But when I replace the call of *max_element(&V[0], &V[0]+n); to *max_element(V.begin(), V.end()); it does compile:
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
int n;
std::cin>>n;
std::vector<int> V(n);
// some initialization here
int max =*max_element(V.begin(), V.end());
}
Could somebody explain me why the two are different?
This is due to argument dependant lookup (aka ADL).
Since max_element is defined in the namespace ::std, you should really write std::max_element everywhere. But, when you use it in its second form
max_element(V.begin(), V.end());
since V.begin() and V.begin() have type defined itself in ::std, ADL kicks in and finds std::max_element.