c++ assertion string iterator offset out of reange - c++

I am getting Assertion Failed. It show it after cin. I have checked also the file whose path it shows, but no solution.
"string iterator + offset out of range" is the massage it shows. It happens after I use "cin >> a" at line 65. Can anyone help me? Thanks in advance.
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int gcd(int a, int b){
cout << "gcd" << endl;
if (b == 0) return a;
else return gcd(b, a % b);
}
int gcd_n(vector<int>nums){
int g;
size_t n = nums.size();
g = nums.at(0);
cout << "son" << endl;
for (int i = 1; i < n; i++){
g = gcd(nums.at(i), g);
}
return g;
}
long long int multi_vect(vector<int> v){
long long int m = 1;
for (size_t i = 0; i < v.size(); i++)
m *= v.at(i);
return m;
}
int main() {
int a;
vector <vector<int>> all_vects;
cin >> a;
string input, sub;
getline(cin, input);
int n = input.find(' ');
vector<int> vect;
while(true){
int num;
sub = input.substr(0, n);
istringstream(sub) >> num;
vect.push_back(num);
input = input.substr(n+1, input.back()+1);
n = input.find(' ');
if (n == -1){
istringstream(input) >> num;
vect.push_back(num);
break;
}
}
all_vects.push_back(vect);
}

When I tested this code, I found that n=-1 needs to be judged in advance. Suppose that input. Assuming that the string input has no ' ', then n will become -1, And the sub = input.substr(0, n); is not true. So, the vector vect will be empty. That is why string iterator + offset out of range will appear.
The following are my changes to this code. And you could refer to it.
if (n == -1)
{
istringstream(input) >> num;
vect.push_back(num);
break;
}
else {
sub = input.substr(0, n);
istringstream(sub) >> num;
vect.push_back(num);
input = input.substr(n + 1, input.back() + 1);
n = input.find(' ');
}

Related

I am trying to add large numbers using arrays without using bigint or anything like that. C++

I am trying to add large numbers using arrays without using bigint or anything like that. I can get my program to add the two arrays. However, I need to take the addition of the arrays and output the correct answer like a regular number. I cannot seem to make an algorithm to take the sum of my arrays and ouptut the answer. Does anybody have any tips or suggestions?
#include <iostream>
#include <string>
#include <iomanip>
#include <algorithm>
#include <iterator>
using namespace std;
const int DIGITS = 20;
void readNum(int list[], int& length, string input1);
void reverseArray(int arr[], int start, int end);
void sumNum(int list1[], int numOfElementsList1,
int list2[], int numOfElementsList2);
int main()
{
// Write your main here
string input1;
string input2;
int list[DIGITS];
int list2[DIGITS];
int total[DIGITS];
int input1Length;
int input2Length;
cout << "Please enter your 1st number: " << endl;
cin >> input1;
cout << "Please enter your 2nd number: " << endl;
cin >> input2;
input1Length = input1.length();
input2Length = input2.length();
readNum(list, input1Length, input1);
readNum(list2, input2Length, input2);
reverseArray(list, 0, input1Length);
reverseArray(list2, 0, input2Length);
sumNum(list, input1Length, list2, input2Length);
}
void readNum(int list[], int& length, string input1)
{
int array[DIGITS];
for (int i = 0; i < length; i++)
{
array[i] = input1[i] - '0';
list[i] = array[i];
}
}
void reverseArray(int arr[], int start, int length)
{
int end;
end = length - 1;
while (start < end)
{
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
void sumNum(int list1[], int numOfElementsList1,
int list2[], int numOfElementsList2)
{
int length;
int sum = 0;
int carry = 0;
int total[DIGITS];
if (numOfElementsList1 > numOfElementsList2)
{
length = numOfElementsList1;
}
else
{
length = numOfElementsList2;
}
for (int i = 0; i < length; i++)
{
sum = list1[i] + list2[i] + carry;
if (sum >= 10)
{
sum = sum % 10;
carry = 1;
}
else
{
carry = 0;
}
total[i] = sum;
cout << total[i];
}
}
Strings are arrays of characters, you could just use them as-is. The advantage being... they're just strings, and you can output them as a string just as easily. Not a new technique, it's called a binary coded decimal which in this case is a zoned BCD (where the zone is 0x30 in ASCII, or zone 0xF0 in EBCDIC).
#include <iostream>
#include <string>
#include <stdexcept>
using std::string;
using std::cout;
using std::cin;
using std::runtime_error;
static string sumNum(string, string);
int main() {
string input1;
string input2;
cout << "Please enter your 1st number: ";
cin >> input1;
cout << "Please enter your 2nd number: ";
cin >> input2;
auto sum = sumNum(input1, input2);
cout << "Sum is: " << sum << "\n";
}
string sumNum(string a, string b) {
//a = string(a.rbegin(), a.rend());
//b = string(b.rbegin(), b.rend());
string sum;
auto digit = [carry = 0](int value) mutable {
value += carry;
if (value > 9) {
carry = 1;
value -= 10;
} else {
carry = 0;
}
return static_cast<char>(value + '0');
};
auto num = [](char c) {
if (c < '0' || c > '9') {
throw runtime_error("not a digit");
}
return c - '0';
};
auto aa = a.rbegin();
auto bb = b.rbegin();
while(aa != a.rend() && bb != b.rend()) {
sum.push_back(digit((num(*aa)) + (num(*bb))));
++aa;
++bb;
}
while (aa != a.rend()) {
sum.push_back(digit(num(*aa)));
++aa;
}
while (bb != b.rend()) {
sum.push_back(digit(num(*bb)));
++bb;
}
char last = digit(0);
if (last != '0')
sum.push_back(last);
return string(sum.rbegin(), sum.rend());
}

C++ code Runtime error on 2D array declaration

I dont understand why is this code giving runtime error on input of any test case (size of string is n, and then string is input). Not even the word "CHECK" (in the solve() function) gets printed.. Please help!
The problem link is : problem
#include <bits/stdc++.h>
using namespace std;
int a[1000][26];
int mov(int l, int u, int x)
{
if(l==u)
{
if(a[l][x]-a[l-1][x]==1)
return 1;
else
return 0;
}
int m=(l+u)/2;
return max(mov(l,m,x+1)+a[u][x]-a[m][x],mov(m,u,x+1)+a[m][x]-a[l-1][x]);
}
void solve()
{
int i,k,j,n;
string str;
cin >> n >> str;
cout << "CHECK";// This is not getting printed
for(i=0;i<26;i++)
a[0][i]=0;
for(i=1;i<n+1;i++)
{
for(j=0;j<26;j++)
{
a[i][j]=a[i-1][j];
if(str[i-1]==j+'a')
a[i][j]++;
}
}
k=mov(1,n,0);
cout << n-k << "\n";
}
int main()
{
int t=1;
cin >> t;
while(t--)
solve();
}
Your very first input shows how many input "pairs" will be given. In your case, you have skipped this part and gone into gathering the input "pairs". This is why "CHECK" wont get printed. To resolve this, have a cin to capture the number of input pairs, then iterate through the inputs to get the pair.
void solve()
{
int i, k, j, n;
string str;
memset(a[0], 0, sizeof(int) * 26); // Use this instead.
cin >> n;
cout << "CHECK";
for (i = 1; i < n + 1; i++)
{
cin >> j >> str;
for (j = 0; j < 26; j++)
{
a[i][j] = a[i - 1][j];
if (str[i - 1] == j + 'a')
a[i][j]++;
}
}
k = mov(1, n, 0);
cout << k << "\n";
}
Also, try not to use using namespace std;.

Inserted in set and received Segmentation fault

I created code to convert graph representation (A list of edges -> the adjacency list)
How can i fix error?
I have Segmentation fault in line res[cur.first - 1].insert(cur.second);for input
4 3
3 2
2 1
4 2
My code
#include <bits/stdc++.h>
using namespace std;
pair<int, int> strToSotredPair(const string& s) {
int a = 0, b = 0;
int pos = 0;
while (s[pos] != ' ') {
a = a * 10 + s[pos] - '0';
++pos;
}
while (pos < s.size()) {
b = b * 10 + s[pos] - '0';
++pos;
}
return {min(a, b), max(a, b)};
}
int main() {
int n, m;
string input;
cin >> n;
cin >> m;
vector<set<int>> res(n, set<int>());
for (int i = 0; i < m; ++i) {
cin >> input;
auto cur = strToSotredPair(input);
res[cur.first - 1].insert(cur.second); // error in this line
}
for (int i = 0; i < res.size(); ++i) {
cout << res[i].size() << ' ';
for (auto item : res[i]) {
cout << item << ' ';
}
cout << endl;
}
}
There are a couple of error's in your code because of which you were getting that error.
You wanted the graph edges as strings. So you need to take edge inputs as strings. For that, you would be required to use getline(cin,input) and cin.ignore().
(My suggestion: Do not take inputs as strings because as it is you are converting them to integers afterwards. By default if you just write cin<<node1<<node2; the two nodes of an edge would have come as integers and function strToSotredPair would not be needed).
In function strToSotredPair after you get the integer a, pos variable is pointing to the space. So you need to increase it by 1 to point to the starting position to 2nd number. Hence a pos++ was needed.
#include <bits/stdc++.h>
using namespace std;
pair<int, int> strToSotredPair(const string& s) {
int a = 0, b = 0;
int pos = 0;
while (s[pos] != ' ') {
a = a * 10 + s[pos] - '0';
++pos;
}
pos++;
while (pos < s.size()) {
b = b * 10 + s[pos] - '0';
++pos;
}
return {min(a, b), max(a, b)};
}
int main() {
int n, m;
string input;
cin >> n;
cin >> m;
vector<set<int>> res(n, set<int>());
cin.ignore(); // To clear the input buffer
for (int i = 0; i < m; ++i) {
getline(cin, input); // to get line by line string inputs
auto cur = strToSotredPair(input);
res[cur.first - 1].insert(cur.second);
}
for (int i = 0; i < res.size(); ++i) {
cout << res[i].size() << ' ';
for (auto item : res[i]) {
cout << item << ' ';
}
cout << endl;
}
}

C++) how to distinct 1.0E+1000 number's aliquot?

If input A < 10^1000 , b = common int <100000
how can Ii know that A is multiple of B or not?
int main()
{
int testcase = 0;
cin >> testcase;
for (int i = 0; i < testcase; i++)
{
long long num;
int div = 0;
cin >> num >> div;
if (num % div == 0)
{
cout << 1 << endl;
}
else
{
cout << 0 << endl;
}
}
return 0;
}
this is what i tried.
The first step is to read (or set) the large number as a string.
The second step consists in convert this string to a vector of int, each int being less than 10000.
The last step is to calculate a modulo b, in the same way we are performing a division by hand
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
std::vector<int> conver_to_vect_int (const std::string &a) {
std::vector<int> x;
int n = a.size();
x.reserve (n/5 + 1);
for (int i = 0; i < n; i += 5) {
int max = std::min (i+5, n);
std::string s (a.begin() + i, a.begin() + max);
int number = std::stoi (s);
x.push_back (number);
}
return x;
}
int modulo (const std::string &a_string, int b) {
std::vector<int> a = conver_to_vect_int (a_string);
int mod = 0;
for (int val: a) {
int val_with_mod = mod * 100000 + val;
mod = val_with_mod % b;
}
return mod;
}
int main() {
std::vector<std::string> list_s = {"29", "111111111", "111111111111111111111111111111111111", "111111111111111211111111111111111111"};
int b = 9;
for (auto &s: list_s) {
int mod = modulo (s, b);
bool divisibility = mod == 0;
std::cout << "divisibility of " << s << " by " << b << " = " << divisibility << "\n";
}
}

Return all codes - String

Assume that the value of a = 1, b = 2, c = 3, ... , z = 26. You are given a numeric string S. Write a program to return the list of all possible codes that can be generated from the given string.
For most of the cases this code works but it gives wrong output for inputs which have numbers greater than 26. For eg: 12345.
#include <iostream>
#include <string.h>
using namespace std;
using namespace std;
int atoi(char a)
{
int i=a-'0';
return i;
}
char itoa(int i)
{
char c='a'+i-1;
return c;
}
int getCodes(string input, string output[10000]) {
if(input.size()==0)
{
return 1;
}
if(input.size()==1)
{
output[0]=output[0]+itoa(atoi(input[0]));
return 1;
}
string result1[10000],result2[10000];
int size2;
int size1=getCodes(input.substr(1),result1);
if(input.size()>1)
{
if(atoi(input[0])*10+atoi(input[1])>10&&atoi(input[0])*10+atoi(input[1])<27)
{
size2=getCodes(input.substr(2),result2);
}
}
for(int i=0;i<size1;i++)
{
output[i]=itoa(atoi(input[0]))+result1[i];
}
for(int i=0;i<size2;i++)
{
output[i+size1]=itoa(atoi(input[0])*10+atoi(input[1]))+result2[i];
}
return size1+size2;
}
int main(){
string input;
cin >> input;
string output[10000];
int count = getCodes(input, output);
for(int i = 0; i < count && i < 10000; i++)
cout << output[i] << endl;
return 0;
}
if i give input 12345, the output is:
"
abcde
awde
lcde
l"
instead of :
"
abcde
awde
lcde"
i got it fellow members. i did not initialised the size2 variable to zero. also i didn't use >= operator.
int getCodes(string input, string output[10000]) {
if(input.size()==0)
{
output[0]="";
return 1;
}
if(input.size()==1)
{
output[0]=itoa(atoi(input[0]));
return 1;
}
string result1[10000],result2[10000];
int size2=0;
int size1=getCodes(input.substr(1),result1);
if(input.size()>1)
{
if(atoi(input[0])*10+atoi(input[1])>=10&&atoi(input[0])*10+atoi(input[1])<27)
{
size2=getCodes(input.substr(2),result2);
}
}
int k=0;
for(int i=0;i<size1;i++)
{
output[k++]=itoa(atoi(input[0]))+result1[i];
}
for(int i=0;i<size2;i++)
{
output[k++]=itoa(atoi(input[0])*10+atoi(input[1]))+result2[i];
}
return k;
}
this is the final code for getCodes function. Thanks everyone :)
You can do that more simply with something like this:
#include <utility>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
void getCodesRec(unsigned int num, string& current, vector<string>& result)
{
// First and last chars for the codes
static constexpr char FIRST_CHAR = 'a';
static constexpr char LAST_CHAR = 'z';
if (num == 0)
{
// When there is no more number add the code to the results
result.push_back(current);
}
else
{
// Add chars to the existing code
unsigned int next = num;
unsigned int rem = next % 10;
unsigned int f = 1;
// While we have not gone over the max char number
// (in practice this loop will run twice at most for a-z letters)
while (next > 0 && rem <= (unsigned int)(LAST_CHAR - FIRST_CHAR) + 1)
{
next = next / 10;
if (rem != 0) // 0 does not have a replacement
{
// Add the corresponding char
current.insert(0, 1, FIRST_CHAR + char(rem - 1));
// Recursive call
getCodesRec(next, current, result);
// Remove the char
current.erase(0, 1);
}
// Add another number
f *= 10;
rem += f * (next % 10);
}
}
}
vector<string> getCodes(unsigned int num)
{
vector<string> result;
string current;
getCodesRec(num, current, result);
return result;
}
int main()
{
unsigned int num = 12345;
vector<string> codes = getCodes(12345);
cout << "Codes for " << num << endl;
for (string& code : codes)
{
cout << "* " << code << endl;
}
return 0;
}
Output:
Codes for 12345
* abcde
* lcde
* awde