Read file from txt using 2d vectors - c++

Is it possible to use the operator [] in case of 2d vectors? For example i got the following code:
vector<vector<string>> data;
ifstream myReadFile;
myReadFile.open("stoixeia_astheni.txt");
while (!myReadFile.eof()) {
for(int i=0; i<1; i++){
for (int j=0; j<4; j++){
myReadFile >> data[i][j];
}
}
}
I got message out of range. I have a file with 5 lines and 4 columns.

Your vector data is empty, its size() is 0. You have to resize it first or add new elements by using push_back():
while (!myReadFile.eof()) {
for(int i = 0; i < 1; i++){
vector<string> tmpVec;
string tmpString
for (int j = 0; j < 4; j++){
myReadFile >> tmpString;
tmpVec.push_back(tmpString);
}
data.push_bac(tmpVec);
}
}
You could also set the size right at the declaration of data:
vector<vector<string>> data(5,vector<string>(4));
ifstream myReadFile;
myReadFile.open("stoixeia_astheni.txt");
while (!myReadFile.eof()) {
for(int i=0; i < 5; i++){
for (int j=0; j<4; j++){
myReadFile >> data[i][j];
}
}
}

Related

Memory allocation error for multiple files “terminate called after throwing an instance of 'std :: bad_alloc' what (): std :: bad_alloc” [C ++]

I am using a classifier algorithm for a digital voice signal processing project. This algorithm was developed to receive all the audio signals in a single vector to do the processing, but I'm having problems, because the number of files I'm working on is very large and is generating the error "terminate called after throwing an instance of ' std :: bad_alloc 'what (): std :: bad_alloc ". I would like to know if it is possible to make any changes to the code that reads the files and stores them in the vector more efficiently, without exceeding the available memory space.
Code for reading the files:
string filename;
filename="C:\\Users\\marcu\\Desktop\\TCC\\Arquivos_10780\\Arquivos_DFT_TXT_512\\PA_D_00";
std::vector<double> c;
for(int j=1; j<=5400; j++)
{
stringstream ss;
ss << filename << setw(5) << setfill('0') << j << "_bonafide_DFT.txt";
std::ifstream f;
f.open(ss.str().c_str());
if (f.is_open())
{
double num;
while (f >> num)
c.push_back(num);
f.close();
}
else
{
f.close();
continue;
}
}
for(int j=5401; j<=29700; j++)
{
stringstream ss;
ss << filename << setw(5) << setfill('0') << j << "_spoof_DFT.txt";
std::ifstream f;
f.open(ss.str().c_str());
if (f.is_open())
{
double num;
while (f >> num)
c.push_back(num);
f.close();
}
else
{
f.close();
continue;
}
}
Full code:
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<stdlib.h>
#include<iomanip>
#include<sstream>
using namespace std;
double mean_similarities(double**,int,int);//vectors, number of vectors, their dimension
int main()
{
const int number_of_classes=2;
int number_of_feature_vectors_in_class[number_of_classes];
number_of_feature_vectors_in_class[0]=2700;
number_of_feature_vectors_in_class[1]=8080;
const int dimension_of_each_feature_vector=512;
////////////////////////////////////////////////////////////////////////////////////////////
/*
Example: 3 classes and 4 vectors of dimension 2 in each class
{{0.90,0.12},{0.88,0.14},{0.88,0.13},{0.89,0.11}} //0.88---0.90 ; 0.11---0.14
{{0.55,0.53},{0.53,0.55},{0.54,0.54},{0.56,0.54}} //0.53---0.56 ; 0.53---0.55
{{0.10,0.88},{0.11,0.86},{0.12,0.87},{0.11,0.88}} //0.10---0.12 ; 0.86---0.88
double c[]={
0.90,0.12,0.88,0.14,0.88,0.13,0.89,0.11,
0.55,0.53,0.53,0.55,0.54,0.54,0.56,0.54,
0.10,0.88,0.11,0.86,0.12,0.87,0.11,0.88
//all vectors in class C_1, followed by all vectors in C_2, ...., followed by all in C_n
};
*/
////////////////////////////////////////////////////////////////////////////////////////////
string filename;
filename="C:\\Users\\marcu\\Desktop\\TCC\\Arquivos_10780\\Arquivos_DFT_TXT_512\\PA_D_00";
std::vector<double> c;
for(int j=1; j<=5400; j++)
{
stringstream ss;
ss << filename << setw(5) << setfill('0') << j << "_bonafide_DFT.txt";
std::ifstream f;
f.open(ss.str().c_str());
if (f.is_open())
{
double num;
while (f >> num)
c.push_back(num);
f.close();
}
else
{
f.close();
continue;
}
}
for(int j=5401; j<=29700; j++)
{
stringstream ss;
ss << filename << setw(5) << setfill('0') << j << "_spoof_DFT.txt";
std::ifstream f;
f.open(ss.str().c_str());
if (f.is_open())
{
double num;
while (f >> num)
c.push_back(num);
f.close();
}
else
{
f.close();
continue;
}
}
////////////////////////////////////////////////////////////////////////////////////////////
//edit whatever you need, according to the feature vectors of your problem, ABOVE this line.
//Do NOT change anything BELOW this line !!!!!
////////////////////////////////////////////////////////////////////////////////////////////
double*** C=new double**[number_of_classes];
for(int i=0; i<number_of_classes; i++)
C[i]=new double*[number_of_feature_vectors_in_class[i]];
for(int i=0; i<number_of_classes; i++)
for(int j=0; j<number_of_feature_vectors_in_class[i]; j++)
C[i][j]=new double[dimension_of_each_feature_vector];
int l=0;
for(int i=0; i<number_of_classes; i++)
for(int j=0; j<number_of_feature_vectors_in_class[i]; j++)
for(int k=0; k<dimension_of_each_feature_vector; k++)
{
C[i][j][k]=c[l];
l++;
}
//Debug info only
//for(int i=0;i<number_of_classes;i++)
// for(int j=0;j<number_of_feature_vectors_in_class[i];j++)
// for(int k=0;k<dimension_of_each_feature_vector;k++)
// printf("\nclass %d vector %d element %d is %.3f",i,j,k,C[i][j][k]);
//getchar();
double Y[number_of_classes];
for(int i=0; i<number_of_classes; i++)
Y[i]=mean_similarities(C[i],number_of_feature_vectors_in_class[i],dimension_of_each_feature_vector);
double alpha=Y[0];
for(int i=1; i<number_of_classes; i++)
if(Y[i]<alpha)
alpha=Y[i];
printf("\nALPHA: %.3f",alpha);
double** smallest_range_vector_for_class=new double*[number_of_classes];
for(int i=0; i<number_of_classes; i++)
smallest_range_vector_for_class[i]=new double[dimension_of_each_feature_vector];
for(int i=0; i<number_of_classes; i++)
for(int k=0; k<dimension_of_each_feature_vector; k++)
smallest_range_vector_for_class[i][k]=C[i][0][k];
for(int i=0; i<number_of_classes; i++)
for(int j=1; j<number_of_feature_vectors_in_class[i]; j++)
for(int k=0; k<dimension_of_each_feature_vector; k++)
if(C[i][j][k]<smallest_range_vector_for_class[i][k])
smallest_range_vector_for_class[i][k]=C[i][j][k];
//Debug info only
//for(int i=0;i<number_of_classes;i++)
// for(int k=0;k<dimension_of_each_feature_vector;k++)
// printf("\nclass %d smallest component %d is %.3f",i,k,smallest_range_vector_for_class[i][k]);
double** largest_range_vector_for_class=new double*[number_of_classes];
for(int i=0; i<number_of_classes; i++)
largest_range_vector_for_class[i]=new double[dimension_of_each_feature_vector];
for(int i=0; i<number_of_classes; i++)
for(int k=0; k<dimension_of_each_feature_vector; k++)
largest_range_vector_for_class[i][k]=C[i][0][k];
for(int i=0; i<number_of_classes; i++)
for(int j=1; j<number_of_feature_vectors_in_class[i]; j++)
for(int k=0; k<dimension_of_each_feature_vector; k++)
if(C[i][j][k]>largest_range_vector_for_class[i][k])
largest_range_vector_for_class[i][k]=C[i][j][k];
//Debug info only
//for(int i=0;i<number_of_classes;i++)
// for(int k=0;k<dimension_of_each_feature_vector;k++)
// printf("\nclass %d largest component %d is %.3f",i,k,largest_range_vector_for_class[i][k]);
int R=0;
int F=0;
for(int ia=0; ia<number_of_classes; ia++)
for(int ib=0; ib<number_of_classes; ib++)
for(int j=0; j<number_of_feature_vectors_in_class[ib]; j++)
for(int k=0; k<dimension_of_each_feature_vector; k++)
{
if(ib!=ia)
{
if((C[ib][j][k]>smallest_range_vector_for_class[ia][k])&&(C[ib][j][k]<largest_range_vector_for_class[ia][k]))
R++;
F++;
}
}
double beta=((double)(R))/((double)(F));
printf("\nBETA: %.3f",beta);
printf("\nP=(G1,G2)=(%.3f,%.3f)",alpha-beta,alpha+beta-1);
printf("\nDistance from P to (1,0): %.3f",sqrt(pow((alpha-beta)-1,2)+pow(alpha+beta-1,2)));
printf("\n\n");
}
/////////////////////////////////////////////
////////////////////////////////////////////
double mean_similarities(double** v,int n, int t)
{
double largest;
double smallest;
double* s=new double[t];
for(int i=0; i<t; i++)
{
smallest=1;
largest=0;
for(int j=0; j<n; j++)
{
if(v[j][i]>largest)
largest=v[j][i];
if(v[j][i]<smallest)
smallest=v[j][i];
}
s[i]=1-(largest-smallest);
}
double m=0;
for(int i=0; i<t; i++)
m+=s[i];
m/=((double)(t));
return(m);
}
PS: to find the best classifier result, I need to change the size of the file size (amount of information for each file) to increasingly larger values. At first with 512 points, but I double this value with each execution until I reach 8192, but when I try with 16384 the code crashes. I am working with 10780 files where each one has the same dimension and I increase it as I check the result.
First of all, you have a lot of problems below:
double** largest_range_vector_for_class=new double*[number_of_classes];
for(int i=0; i<number_of_classes; i++)
largest_range_vector_for_class[i]=new double[dimension_of_each_feature_vector];
for(int i=0; i<number_of_classes; i++)
for(int k=0; k<dimension_of_each_feature_vector; k++)
largest_range_vector_for_class[i][k]=C[i][0][k];
for(int i=0; i<number_of_classes; i++)
for(int j=1; j<number_of_feature_vectors_in_class[i]; j++)
for(int k=0; k<dimension_of_each_feature_vector; k++)
if(C[i][j][k]>largest_range_vector_for_class[i][k])
largest_range_vector_for_class[i][k]=C[i][j][k];
I can't even read that, but I do get the gist of it, basically you created a dynamic array, a 3D dynamic array, but nowhere in your program did you free the memory that was used by the 3D array, it looks very leaky, I cannot delete for you because I have trouble reading that monstersity....

Moving through every character in a string array

I am trying to go through every string index and print the even indexes first and then print all the odd indexes. However I am getting a segmentation error and I don't know what it is caused by.
Here is my code:
int sum;
vector<string> array;
string temp;
for (int i = 0; i < num; i++) {
cin >> array[i];
}
for (int i = 0; i < num; i++) {
temp = array[i];
for (int j = 0; j < temp.size(); j++) {
sum = j;
if (sum % 2 == 0) {
cout << array[i][j];
}
}
}
cout << " ";
for (int i = 0; i < num; i++) {
temp = array[i];
for (int j = 0; j < temp.size(); j++) {
sum = j;
if (sum % 2 != 0) {
cout << array[i][j];
}
}
}
Does anyone see what I am doing wrong?
You are not populating the array correctly, so your loops are going out of bounds.
Try something more like this instead:
vector<string> array;
string temp;
array.resize(num);
for(int i = 0; i < num; ++i)
{
cin >> array[i];
}
/* Alternatively:
for(int i = 0; i < num; ++i)
{
cin >> temp;
array.push_back(temp);
}
*/
/* Alternatively:
copy_n(istream_iterator<string>(cin), num, back_inserter(array));
*/
for(int i = 0; i < num; ++i)
{
temp = array[i];
for(int j = 0; j < temp.size(); j += 2)
{
cout << temp[j];
}
}
cout << " ";
for(int i = 0; i < num; ++i)
{
temp = array[i];
for(int j = 1; j < temp.size(); j += 2)
{
cout << temp[j];
}
}
vector<string> array is an empty vector, but you're trying to access its ith value with cin >> array[i]; in the first loop, thus getting out of bounds (there's no ith index!) and a segfault.
You should append new values to the vector dynamically or pre-allocate the needed amount of space:
// in the first loop
string test;
cin >> test;
array.push_back(test);
Another option:
// change the declaration
vector<string> array(num); // a vector of size num
// or pre-allocate memory after initialisation
vector<string> array;
array.resize(num);
// then the loop...
You have not declared the size of the std::vector <std::string> array and you are trying to index it which gives segmentation fault. You can use array.push_back() to insert the values, or you have to define the size while declaring the vector.
Either:
std::vector <std::string> array (num); // given num is known beforehand
Or:
vector<string> array;
string temp;
for (int i = 0; i < num; i++) {
cin >> temp;
array.push_back(temp);
}

Output and input a 3D array

I am working on a c++ code and want to output my 3d array to a txt file. And then, input the content of this 3d file into another c++ code.
//Assume that I have a function named Function() that returns float numbers.
double array1[10][20][30];
ofstream out1("3Darray.txt");
for(int i=0; i< 10; i++){
for(int j=0; j< 20; j++){
for(int k=0; k< 30; k++){
out1 << Function() << " ";
}
}
}
//Now, input it into the array.
ifstream file("3Darray.txt");
for(int i=0; i< 10; i++){
for(int j=0; j< 20; j++){
for(int k=0; k< 30; k++){
file >> array1[i][j][k];
}
}
}
This gives me segmentation fault. What am I doing wrong?

Input element by user into 2D vector c++

I'a trying to implement an algorithm, i want to input element by the user into 2D vector so that I have an element like this:
reference 1:
1 2 3
3 2 1
1 2 3
so I want to know how to push_back the element into 2D vector
my problem here:
std::vector<vector<int>> d;
//std::vector<int> d;
cout<<"Enter the N number of ship and port:"<<endl;
cin>>in;
cout<<"\Enter preference etc..:\n";
for(i=0; i<in; i++){
cout<<"ship"<<i+1<<":"<<' ';
for(j=0; j<in; j++){
cin>>temp;
d.push_back(temp);// I don't know how to push_back here!!
}
}
Here is the solution
std::vector<vector<int>> d;
//std::vector<int> d;
cout<<"Enter the N number of ship and port:"<<endl;
cin>>in;
cout<<"\Enter preference etc..:\n";
for(i=0; i<in; i++){
cout<<"ship"<<i+1<<":"<<' ';
for(j=0; j<in; j++){
cin>>temp;
d[i].push_back(temp);
}
}
C++ is a strong type language, d is a vector of vector:
for(i=0; i<in; i++){
cout<<"ship"<<i+1<<":"<<' ';
vector<int> row;
for(j=0; j<in; j++){
cin>>temp;
row.push_back(temp);// I don't know how to push_back here!!
}
d.push_back(row);
}
This should work:
vector<vector<int> > d;
int val;
for(int i = 0; i < in; i++){
vector<int> temp;
for(int j = 0; j < in; j++){
cin >> val;
temp.push_back(val);
}
d.push_back(temp);
temp.clear();
}
In general, we can add elements in a 2D matrix of vectors according to a similar approach as mentioned below :
#include<bits/stdc++.h>
using namespace std;
int main() {
int row,col;
cin>>row>>col;
vector<vector<int>>matrix;
for(int i=0;i<row;i++){
vector<int>temp;
for(int j=0;j<col;j++){
int val;
cin>>val;
temp.push_back(val);
}
matrix.push_back(temp);
}
return 0;
}
d[x].push_back(y);
This should work for you.
There are two methods to perform this task:
vector<vector<int> > v;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
v[i].push_back(data);
}}
vector<vector<int> > v;
for(int i=0;i<n;i++){
vector<int> x;
for(int j=0;j<m;j++) x[j].push_back(data);
v.push_back(x);
}
/* Below takes user input for n x n array */
vector<vector <int>> arr(n);
for (int i = 0; i < n; i++) {
arr[i].resize(n);
for (int j = 0; j < n; j++) {
cin >> arr[i][j];
}
}
This is what you can do
int in;
std::cout << "Enter the N number of ship and port:" << std::endl;
std::cin >> in;
// declare a vector d of size 'in' containing vectors of size 0;
std::vector<std::vector<int>> d(in, std::vector<int>());
std::cout << "\Enter preference etc..:\n";
for(i=0; i<in; i++){
std::cout << "ship" << i+1 << ":" << ' ';
for(j=0; j<in; j++){
int temp;
std::cin >> temp;
d[i].push_back(temp); // now you can push_back here!!
}
}
#include <iostream>
#include <vector>
using namespace std;
int main() {
int N;
cout << "Please enter the no. of edges: ";
cin >> N;
vector<vector<int>> outer;
for(int i = 0; i < N; i++)
{
vector<int> temp;
for(int j = 0; j < 1; j++)
{
int u, v;
cin >> u;
cin >> v;
temp.push_back(u);
temp.push_back(v);
};
outer.push_back(temp);
temp.clear();
};
for(int i = 0; i<outer.size(); i++)
{
for(int j = 0; j < outer[i].size(); j++)
{
cout<<" "<<outer[i][j];
};
cout<<endl;
};
};
//this is a solution and it litrally works give it a try
//v(n) is must
//thats why your sol was giving problem
//we must specify rows
int main()
{
int value;
vector<vector<int>> v(n);
for(int i=0;i<n;++i)
{
for(int j=0;j<n;++j)
{
cin>>value;
v[i].push_back(value);
}
}
return 0;
}
vector<vector<int>> matrix; //declaring 2D vactor as matrix
int val;
cin>>val; //reading size of matrix in val
for(int i=0;i<val;i++){
vector<int> temp; //make temp vector for storing val for every iteration
for(int j=0;j<val;j++){
int x;
cin>>x;
temp.emplace_back(x);
}
matrix.emplace_back(temp); // push back to matrix, temp vector's all value for every iteration
temp.clear(); // clear temp vector for every iteration
}

2d array addition in c++

i am trying to add two 2D arrays in C++ with my following code by i am getting output as this
333 333, but i want out as 2 rows
{
int a[2][3], b[2][3], i , j;
cout<<"First Matrix"<<endl;
for (int i=0; i<2; i++)
{
for (int j=0; j<3; j++)
{
cin>>a[i] [j];
}
}
cout<<"Second Matrix"<<endl;
for(int i=0; i<2; i++)
{
for (int j=0; j<3; j++)
{
cin>>b[i][j];
}
}
for (int i=0; i<2; i++)
{
for (int j=0; j<3; j++)
{
cout<<a[i] [j] + b[i] [j];
}
cout<<" ";
}
cout<<endl;
_getch();
}
Last for loop is wrong. You have to move cout's.
for (int i=0; i<2; i++)
{
for (int j=0; j<3; j++)
{
cout<<a[i] [j] + b[i] [j];
cout<<" ";
}
cout<<endl;
}
Also your variables i and j are unused because you are declaring new ones in for loops with int i=0; and int j=0;.
How about changing the line that prints spaces to print a newline?
cout<<" ";
becomes
cout<<"\n";
You don't put any newlines in your code, so of course it won't print out on a new line. replace cout<<" "; with cout<<std::endl; and you should get each row on a new line.
Replace the last piece of code by this:
for (int i=0; i<2; i++)
{
for (int j=0; j<3; j++)
{
cout<<a[i] [j] + b[i] [j] << ' ';
}
cout<< "\n";
}
cout << "\n";