I tried many things but still, it's giving an error:
no matching function for call to ‘begin(int [n])’
What's the best approach?
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
int arr[n];
for(int i = 0; i < n; i++){
cin >> arr[i];
}
reverse(begin(arr), end(arr));
for(int j = 0; j < n; j++){
cout << arr[j] <<" ";
}
return 0;
}
error:no matching function for call to ‘begin(int [n])’
This is because of that you have used non-standard Variable Length Array, here:
cin >> n;
int arr[n] ;
Therefore, it's not possible to apply the standard algorithms like std::reverse to this kind of non-standard arrays.
if you change it normal array with a size, like:
const int n = 3;
int arr[n] ;
The code what you wrote is valid and will work. See here
However, now you can not input the size of the array.
Whats the best approach?
Use std::vector instead.
Now you also have the option for reverse printing without using std::reverse, but using std::vector::reverse_iterator.(If that's all you wanted)
For instance: See output here
#include <vector>
#include <iostream>
#include <algorithm>
int main()
{
int n;
std::cin >> n;
std::vector<int> arr(n);
for(int& ele: arr) std::cin >> ele;
//std::reverse(std::begin(arr), std::end(arr));
//for(const int ele: arr) std::cout << ele << " ";
//or simply
std::for_each(arr.rbegin(), arr.rend(),[](const int ele){ std::cout << ele << " "; });
return 0;
}
Related
Hello guys so this is my code.
I could not use cin nor getline() so I had to use scanf.
It reads all the values in as expected but after entering the last value it says:
free(): invalid pointer ./comp: line 8: 877 Aborted (core dumped) ./$BIN
Anyways, here is the code.
Help would be appreciated.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
// n -> amount of lines of code.
// q -> amount of queries.
int n, q;
cin >> n >> q;
// Handle source code Input.
vector<string> v(n);
for (unsigned i = 0; i < n; ++i)
{
cout << "i: " << i << endl;
scanf("%s", &v[i]);
}
return 0;
}
scanf is designed to work with character buffers, not strings. You probably want to use std::string (it's more intuitive and manages memory for you), so scanf is a poor fit. There's a version of getline that works with string.
std::vector<std::string> v(n);
for (int i = 0; i < n; i++) {
cout << "i: " << i << endl;
std::getline(std::cin, v[i]);
}
The %s specifier of scanf() expects a pointer to a char[] array, not a std::string object. By reading directly into a std::string object, you are corrupting its internals.
So, you need to either:
read into a char[] first, then assign that to your std::string:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
// n -> amount of lines of code.
// q -> amount of queries.
int n, q;
cin >> n >> q;
// Handle source code Input.
vector<string> v(n);
char buf[256];
for (unsigned i = 0; i < n; ++i)
{
cout << "i: " << i << endl;
scanf("%255s", buf);
v[i] = buf;
/* or:
int len = scanf("%255s", buf);
v[i] = string(buf, len);
*/
}
return 0;
}
pre-allocate the std::string's internal character buffer, then read directly into it (note, this approach is only guaranteed to work in C++11 and later, but in practice will typically work in most implementations of std::string in earlier versions, too):
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
// n -> amount of lines of code.
// q -> amount of queries.
int n, q;
cin >> n >> q;
// Handle source code Input.
vector<string> v(n);
for (unsigned i = 0; i < n; ++i)
{
cout << "i: " << i << endl;
v[i].resize(256);
int len = scanf("%255s", &v[i][0]/* or: v[i].data() in C++17 and later */);
v[i].resize(len);
}
return 0;
}
For solving problems on Leetcode, Kickstart or other competitive competitions, we need to take input of multiple integers in a single line and store them in an array or vector, like
Input : 5 9 2 5 1 0
int arr[6];
for (int i = 0; i < 6; i++)
cin >> arr[i];
or
vector<int> input_vec;
int x;
for (int i = 0; i < 6; i++) {
cin >> x;
input_vec.push_back(x);
}
This works, but also contributes to the execution time drastically, sometimes 50% of the execution time goes into taking input, in Python3 it's a one-line code.
input_list = list(int(x) for x in (input().split()))
But, couldn't find a solution in C++.
Is there a better way to do it in c++?
Take the help of std::istringstream:
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
int main(void) {
std::string line;
std::vector<int> numbers;
int temp;
std::cout << "Enter some numbers: ";
std::getline(std::cin, line);
std::istringstream ss(line);
while (ss >> temp)
numbers.push_back(temp);
for (size_t i = 0, len = numbers.size(); i < len; i++)
std::cout << numbers[i] << ' ';
return 0;
}
How to take multiple integers in the same line as an input and store them in an array or vector in c++?
Like this:
int arr[6]; for(int i=0;i<6;i++){ cin>>arr[i]; }
beginner here
i wrote the below in C++, it's a short program that currently takes 2 words as inputs, and outputs the same words back but the words are split into even and odd instead. I would like to be able to do this for 'T' words instead, but I can't figure it out. I would like to be able to first input the number of words that will follow, for example 10. Then to input the words and get T results back. So instead of just 2 words, an unlimited amount with the user specifying.
I need to put the below into a function and go from there sometime, but I want to learn the best technique to do so - any advice please?
Thanks!
Alex
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
int T;
cin >> T;
string FirstWord;
cin >> FirstWord;
int LengthFirst;
LengthFirst = FirstWord.length();
string EvenFirst;
string OddFirst;
for (int i = 0; i < LengthFirst; i += 2){
EvenFirst = EvenFirst + FirstWord[i];
}
for (int i = 1; i < LengthFirst; i += 2){
OddFirst = OddFirst + FirstWord[i];
}
string SecondWord;
cin >> SecondWord;
int LengthSecond;
LengthSecond = SecondWord.length();
string EvenSecond;
string OddSecond;
for (int i = 0; i < LengthSecond; i += 2){
EvenSecond += SecondWord[i];
}
for (int i = 1; i < LengthSecond; i += 2){
OddSecond += SecondWord[i];
}
cout << EvenFirst << " " << OddFirst << endl;
cout << EvenSecond << " " << OddSecond << endl;
return 0;
}
Think I got it here, I was over-thinking this one
I put it in a for loop, as below - so any number of words can be input, user has to input the number of test cases at the
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
int T;
cin >> T;
for (int i = 0; i < T; i++){
string FirstWord;
cin >> FirstWord;
int LengthFirst;
LengthFirst = FirstWord.length();
string EvenFirst;
string OddFirst;
for (int i = 0; i < LengthFirst; i += 2){
EvenFirst = EvenFirst + FirstWord[i];
}
for (int i = 1; i < LengthFirst; i += 2){
OddFirst = OddFirst + FirstWord[i];
}
cout << EvenFirst << " " << OddFirst << endl;
}
return 0;
}
Ultimately, you are performing the same task N times.
First, let's discuss how to store the information. Functionally, we have one string as input which yields two strings as output. std::pair (from <utility>) lets us easily represent this. But for sake of even-odd, std::array might be a better representation for us. Since we have a variable number of words as input, a variable number of std::array will be output. std::vector (from <vector>) is our friend here.
Second, let's discuss how to process the information. Using named variables for each output component does not scale, so let's switch to a fixed array (noted below as array<string,2>. By switching to a fixed array for output, addressing each split becomes a function of the loop index (index % 2). Below is a solution that generalizes on a known split size at compile time.
#include <string>
#include <array>
#include <vector>
#include <iostream>
int main() {
int N;
std::cin >> N;
constexpr const int Split = 2;
using StringPack = std::array<std::string, Split>;
std::vector<StringPack> output;
for (int wordIndex = 0; wordIndex < N; ++wordIndex) {
std::string word;
std::cin >> word;
StringPack out;
{
int index = 0;
for (char c : word) {
out[index % Split] += c;
++index;
}
}
output.emplace_back(out);
}
for (const auto & out : output) {
for (const auto & word : out) {
std::cout << word << ' ';
}
std::cout << '\n';
}
}
i need to get couple integer numbers and put them into an array in c++.
assume the count of numbers in CIN are the same count as array length.
int numbers[10];
cin>>numbers;
In fact i want to enter 10 numbers to cin within one line somehow it automatically allocates the numbers to array. how should i do it?
Here is a C++11 solution using std::vector and std::copy_n.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<int> v;
std::copy_n(std::istream_iterator<int>(std::cin), 3, std::back_inserter(v));
}
You can use a loop:
#include <iostream>
int main()
{
int numbers[10];
for (int i = 0; i < 10; ++i)
std::cin >> numbers[i];
}
UPDATE:
If it has to be one line then you could use this (somewhat clumsy solution):
#include <iostream>
int main()
{
int numbers[3];
std::cin >> numbers[0] >> numbers[1] >> numbers[2];
}
Alternatively, you can use std::cin.getline and then parse the string.
UPDATE (again):
#include <iostream>
int main()
{
int numbers[3];
int* input = numbers;
while (std::cin >> *input++ and input != 3 + numbers) ;
}
I have an assignment in which I have to read from a file called ("random.txt") output the total and copy the file into an array dynamically. Then sort the values in the file.
Up until line 20 my programs runs fine and outputs my total values as well as all the numbers in file.
Line 21 onward also runs but then it doesn't output the total I had in line 20 when I run it and it also doesn't display the values in order.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream fin;
int n=0;
double temp;
fin.open("data.txt");
fin>>temp;
while(fin)
{
n++;
fin>>temp;
cout<<temp<<endl;
}
cout<<"Total:"<<n<<endl;
fin.close(); //Program run fine up to here.
fin.open("data.txt");
double *A;
A=new double[n];
for (int i=0;i<n-1;i++)
for (int j=i;j<n;j++)
if (A[i]>A[j])
{
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
for (int i=0;i<n;i++)
{
while(fin)
{
n++;
fin>>A[i];
cout<<"Array:"<<A[i]<<endl;//Program runs up to here as well but
//but now doesn't print out the total I
//had in my program above and just
//prints A[i] and its not even sorted.
}
}
fin.close();
}
I know I have a lot of errors, I'm very new to c++ so I'm still trying to learn. To be quite honest I don't know what I'm doing starting from line 32. I understand that I sorted my array from 24-31, but I don't know how to read my file into my array or how to format it.
Your array load is in the wrong location. It should be before the sort, but after the allocation:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream fin("data.txt");
double temp;
size_t n = 0;
while(fin >> temp)
{
std::cout << temp << ' ';
++n;
}
std::cout << "Total: "<< n << endl;
fin.close();
if (n > 0)
{
fin.open("data.txt");
double *A = new double[n];
for (int i=0; i<n && fin >> A[i]; ++i);
fin.close();
for (int i=0;i<n-1;i++)
{
for (int j=i;j<n;j++)
{
if (A[i]>A[j])
{
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
}
for (int i=0; i<n; i++)
cout << "Array[" << i << "]: " << A[i] << endl;
delete [] A;
}
}
Honestly, there are much better ways to do this. Using the standard library containers, this entire menagerie is reduced to...
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
int main()
{
std::ifstream fin("data.txt");
std::vector<double> A{
std::istream_iterator<double>(fin),
std::istream_iterator<double>() };
std::sort(std::begin(A), std::end(A));
for (auto x : A)
std::cout << x << '\n';
}
You need to assign values to the elements of A before you can sort or read from A!
Your sort in lines 24-31 is misplaced. A is defined on lines 22 and 23 but never initialized. I think you meant to read it from data.txt after reopening on line 21 but you did not.