Using arrays to read and write from fstream? - c++11

MAXSIZE set to 100, first menu option is supposed to check if there is size in the array, read from file and write to first slot of title[] array. I am quite lost.
switch (menu)
{
case 1:
while (getline(infile) < MAXSIZE)
void readMovies(ifstream &infile, int year[], string title[], int &size){
string tmp_title;
int tmp_year;
while (getline(infile, tmp_title)
{
infile >> tmp_year;
infile.ignore();
year [size] = tmp_year;
title[size] = tmp_title;
size++;
}
break;}

This is a MWE of how to copy from a file to another file
#include <algorithm>
#include <fstream>
#include <iterator>
int main() {
std::ifstream ifs("input");
std::ofstream ofs("output");
std::copy(std::istream_iterator<int>(ifs),
std::istream_iterator<int>(),
std::ostream_iterator<int>(ofs, ", "));
}
Given the file input with content 1 2 3 4 5, the output file will be filled with 1, 2, 3, 4, 5,.

Related

How to copy characters into string vector

Attempting to copy from a character vector to a string vector has been unsuccessful across multiple attempts at a solution
allocating memory to the vector prior to copying allows std::copy to work properly when placed at "OutputIterator result" (based on function template). I attempted:
std::copy(char1.begin(), char1.end(), v1.begin());
however, this was unsuccessful as well. using back_inserter returns error c2679 "binary '=': no operator found which takes a right-hand operand of type'char' (or there is no acceptable conversion).
input file is located here: https://adventofcode.com/2018/day/2
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>
#include <algorithm>
#include <iterator>
#include <cstdio>
int main() {
std::string field1;
std::string field2;
char characters;
std::vector<char>::iterator ptr;
std::vector<char>::iterator ptr2;
std::vector<char> char1;
std::vector<char> char2;
int size = 0;
std::ifstream inFile;
inFile.open("C:\\Users\\Administrator\\Desktop\\c++ files\\input2.txt");
if (!inFile) {
std::cout << "abort";
return 1;
}
while (inFile >> characters) { //read variables from input stream
char1.push_back(characters);
}
std::vector<std::string> v1(6500);
std::copy(char1.begin(), char1.end(), std::back_inserter(v1));
inFile.close();
return 0;
}
//26
expect vector v1 to hold values in vector char1. I am assuming the problem stems from the data type of v1 vs. char1, however, I have not been able to find a concrete solution. I do not want to read directly into a string vector; hence my current problem.
I am not sure what you try to achieve. Here few examples:
#include <string>
#include <vector>
int main()
{
std::string str1{ "Just for an example" }; // You can read it from a file
std::vector<std::string> vct_str1(32); // Lets say it has 32 std::string items
std::vector<std::string> vct_str2(32); // Lets say it has 32 std::string items
// **** A. Copy from std::string to std::vector<char>: ****
std::vector<char> vct_ch(str1.begin(), str1.end()); // On construction
// Or later: vct_ch.assign(str1.begin(), str1.end());
// **** B. Copy from std::vector<char> to std::string: ****
std::string str2(vct_ch.begin(), vct_ch.end()); // On construction
// Or later: str2.assign(vct_ch.begin(), vct_ch.end());
// **** C. Copy from std::vector<char> to std::vector<std::string>: ****
vct_str1[0].assign(vct_ch.begin(), vct_ch.end()); // Which is similar to B
// **** D. Source & Dest Types same as in Case-C But char per std::string: ****
int i = 0;
vct_str2.resize(vct_ch.size());
for (auto item : vct_ch)
vct_str2[i++] = item;
return 0;
}

Why is the output different? (putting array in a function problem)

I want the output to be: 1 2 2 2
But why is the output: 1 2 3 4
What's wrong with this code?
#include <iostream>
using namespace std;
int arr[] = {0};
int pluss(int ar[],int a){
ar[0]++;
cout<<ar[0]<<endl;
if(a==0){
pluss(ar,a+1);
pluss(ar,a+1);
pluss(ar,a+1);
}
}
int main() {
pluss(arr,0);
return 0;
}
EDIT: So, the "ar" is global and not local to one child function? how to make it so the "ar" is only local to one child function? I mean: the "ar" in the first pluss(ar,1) is different from the "ar" in the second pluss(ar,2)?
Your code is equivalent of :
int main() {
pluss(arr,0);
pluss(arr,1);
pluss(arr,1);
pluss(arr,1);
return 0;
}
Since each call to pluss definitely increments the array element, before printing it, expected output is 1, 2, 3, 4.
how to make it so the "ar" is only local to one child function?
If you don't like to pass each array element as integer value, you could wrap the array in a struct, since structures are passed by value rather than by reference.
#include <iostream>
using namespace std;
struct s { int a[1]; } arr = {0};
int pluss(struct s ar, int a)
{
ar.a[0]++;
cout <<ar.a[0] <<endl;
if (a==0)
{
pluss(ar, a+1);
pluss(ar, a+1);
pluss(ar, a+1);
}
}
int main()
{
pluss(arr, 0);
return 0;
}

OpenCV and Mat::forEach operator not working in full image

I am trying to segment a depth image, so that values of depth between limits (low and high) remain the same, and values outside limits are set to 0.
To accomplish this I am trying to use the forEach method in OpenCV 3, to speed up the operation using all the available cores of the CPU.
Implementing the function this way, it works:
void Filter_Image(cv::Mat &img, int low, int high)
{
for (uint8_t &p : cv::Mat_<uint8_t>(img))
{
if(((p > low) && (p < high)) == false)
p = 0;
}
}
However, when I try to use the lambda expression, I only get correct results in one vertical third of the image (if you splitted the image in 3 columns, I only get the first left column well segmented). The code is as follows:
void Filter_Image(cv::Mat &img, int low, int high)
{
img.forEach<uint8_t>([&](uint8_t &p, const int * position) -> void {
if(((p > low) && (p < high)) == false)
p = 0;
});
}
The functions are called from this piece of code (simplified for testing):
#include "opencv/cv.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include "config_parser.h"
#include "background_substractor.h"
#include "object_tracker.h"
#include "roi_processing.h"
#include "filtering_functions.h"
using namespace cv;
int main(int argc, char **argv)
{
Mat opencv_frame;
namedWindow("Input Video");
//parse config
VIDEO_CONFIG videoConfig;
BACK_SUBS_CONFIG backSubsConfig;
TRACKER_CONFIG trackerConfig;
ROI_CONFIG roiConfig;
FILTERING_DATA filteringData;
Parse_Config("../Config/ConfigDepthImage.json", videoConfig, backSubsConfig, trackerConfig, filteringData, roiConfig);
Display_Config(videoConfig, backSubsConfig, trackerConfig, filteringData, roiConfig);
VideoCapture videoInput(videoConfig.path.c_str());
if (!videoInput.isOpened())
{
std::cout<<"Could not open reference video"<<std::endl;
return -1;
}
while (1)
{
videoInput >> opencv_frame;
if(opencv_frame.empty())
{
std::cout<<"Empty frame"<<std::endl;
destroyWindow("Input Video");
destroyWindow("Filtered Video");
break;
}
Filter_Image(opencv_frame, filteringData.min, filteringData.max);
//show video
imshow("Input Video", opencv_frame);
waitKey((1.0/videoConfig.fps)*1000);
}
return 0;
}
The difference in results can be observed in the displayed images:
This is the good one:
And this is the bad result in the same conditions using forEach:
I cannot see the error or the difference between the two functions. The type of the image is CV_8UC1.
Could anyone provide a clue?
Thank yo all very much in advance.

Issue in pointer while writing to file. segmentation fault

I am trying to write sequence of bytes into a binary file.
Converting structures into binary and storing in a pointer, and increment the pointer with the same size, before that i hold the address of that pointer into another so at the end i can write whole data from start to end into the file.
here is a code:
#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
struct OhlData_struct
{
int volume;
}__attribute__((__packed__));
struct StrCar
{
int PhoneNo;
long Model;
}__attribute__((__packed__));
int main()
{
StrCar Car;
OhlData_struct header;
char *Data=(char *)calloc(0,(sizeof(OhlData_struct) + (sizeof(StrCar) * 10)));
char *temp;
temp = Data;
string filename = "mydatastream_binary.txt";
ofstream outfile;
outfile.open (filename.c_str(), ios::out | ios::binary);
header.volume=123;
memcpy(Data,(char*) &header, sizeof(struct OhlData_struct));
Data += sizeof(struct OhlData_struct);
int i=0;
while(i <10)
{
Car.PhoneNo=101+i;
Car.Model=1001+i;
memcpy(Data,(char*) &Car, sizeof(struct StrCar));
outfile_copy.write (Data, sizeof(StrCar));
Data += sizeof(struct StrCar);
i++;
}
outfile.write (temp, (sizeof(struct OhlData_struct) + (sizeof(struct StrCar) * 10)));
cout << "\n\nFile writeing done\n\n";
outfile.write gives "sagmentation fault";
can anyone tell how to write whole DATA into the file ? where do I need to change the code!!
Tried a lot, but still not able to get the exact binary data into file,
I am new to C++ and this pointers are out of my mind.

How make a stride chunk iterator thrust cuda

I need a class iterator like this
https://github.com/thrust/thrust/blob/master/examples/strided_range.cu
but that this new iterator do the next sequence
[k * size_stride, k * size_stride+1, ...,k * size_stride+size_chunk-1,...]
with
k = 0,1,...,N
Example:
size_stride = 8
size_chunk = 3
N = 3
then the sequence is
[0,1,2,8,9,10,16,17,18,24,25,26]
I don't know how do this efficiently...
The strided range interator is basically a carefully crafted permutation iterator with a functor that gives the appropriate indices for permutation.
Here is a modification to the strided range iterator example. The main changes were:
include the chunk size as an iterator parameter
modify the functor that provides the indices for the permutation iterator to spit out the desired sequence
adjust the definitions of .end() iterator to provide the appropriate length of sequence.
Worked example:
$ cat t1280.cu
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/iterator/permutation_iterator.h>
#include <thrust/functional.h>
#include <thrust/fill.h>
#include <thrust/device_vector.h>
#include <thrust/copy.h>
#include <thrust/sequence.h>
#include <iostream>
#include <assert.h>
// this example illustrates how to make strided-chunk access to a range of values
// examples:
// strided_chunk_range([0, 1, 2, 3, 4, 5, 6], 1,1) -> [0, 1, 2, 3, 4, 5, 6]
// strided_chunk_range([0, 1, 2, 3, 4, 5, 6], 2,1) -> [0, 2, 4, 6]
// strided_chunk_range([0, 1, 2, 3, 4, 5, 6], 3,2) -> [0 ,1, 3, 4, 6]
// ...
template <typename Iterator>
class strided_chunk_range
{
public:
typedef typename thrust::iterator_difference<Iterator>::type difference_type;
struct stride_functor : public thrust::unary_function<difference_type,difference_type>
{
difference_type stride;
int chunk;
stride_functor(difference_type stride, int chunk)
: stride(stride), chunk(chunk) {}
__host__ __device__
difference_type operator()(const difference_type& i) const
{
int pos = i/chunk;
return ((pos * stride) + (i-(pos*chunk)));
}
};
typedef typename thrust::counting_iterator<difference_type> CountingIterator;
typedef typename thrust::transform_iterator<stride_functor, CountingIterator> TransformIterator;
typedef typename thrust::permutation_iterator<Iterator,TransformIterator> PermutationIterator;
// type of the strided_range iterator
typedef PermutationIterator iterator;
// construct strided_range for the range [first,last)
strided_chunk_range(Iterator first, Iterator last, difference_type stride, int chunk)
: first(first), last(last), stride(stride), chunk(chunk) {assert(chunk<=stride);}
iterator begin(void) const
{
return PermutationIterator(first, TransformIterator(CountingIterator(0), stride_functor(stride, chunk)));
}
iterator end(void) const
{
int lmf = last-first;
int nfs = lmf/stride;
int rem = lmf-(nfs*stride);
return begin() + (nfs*chunk) + ((rem<chunk)?rem:chunk);
}
protected:
Iterator first;
Iterator last;
difference_type stride;
int chunk;
};
int main(void)
{
thrust::device_vector<int> data(50);
thrust::sequence(data.begin(), data.end());
typedef thrust::device_vector<int>::iterator Iterator;
// create strided_chunk_range
std::cout << "stride 3, chunk 2, length 7" << std::endl;
strided_chunk_range<Iterator> scr1(data.begin(), data.begin()+7, 3, 2);
thrust::copy(scr1.begin(), scr1.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl;
std::cout << "stride 8, chunk 3, length 50" << std::endl;
strided_chunk_range<Iterator> scr(data.begin(), data.end(), 8, 3);
thrust::copy(scr.begin(), scr.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl;
return 0;
}
$ nvcc -arch=sm_35 -o t1280 t1280.cu
$ ./t1280
stride 3, chunk 2, length 7
0 1 3 4 6
stride 8, chunk 3, length 50
0 1 2 8 9 10 16 17 18 24 25 26 32 33 34 40 41 42 48 49
$
This is probably not the most optimal implementation, in particular because we are doing division in the permutation functor, but it should get you started.
I assume (and test for) chunk<=stride, because this seemed reasonable to me, and simplified my thought process. I'm sure it could be modified, with an appropriate example of what sequence you would like to see, for the case where chunk>stride.

Resources