I'm having some trouble printing an array of lists (ex. list<string> hashTable[100] )
Heres what I have so far, my question is at the bottom:
hash2.h
1 #ifndef __HASH2_H
2 #define __HASH2_H
3
4 #include<string>
5 #include<list>
6 #include<fstream>
7
8 using namespace std;
9
10 class Hash
11 {
12 public:
13 void processFile(string fileName);
14 void print();
15
16 private:
17 list<string> hashTable[100];
18
19 private:
20 int hf(string ins);
21
22
23 };
24
25 #endif
hash_function2.cpp
1 #include<iostream>
2 #include<string>
3 #include<fstream>
4 #include "hash2.h"
5
6 using namespace std;
7
8 void Hash::processFile(string fileName)
9 {
10 string word;
11 ifstream myIfile(fileName.c_str());
12 while(getline(myIfile, word))
13 {
14 int index = hf(word);
15 hashTable[index].push_back(word);
16 }
17 myIfile.close();
18 }
19
20 void Hash::print()
21 {
22 for(int i = 0; i < 100; i++)
23 {
24 if(hashTable[i] != NULL)
25 {
26 list<int>::iterator i;
27 for(i = hashTable[i].begin(); i != hashTable[i].end(); ++i)
28 {
29 cout << *i << endl;
30 }
31 }
32 }
33 }
34
35 int Hash::hf(string ins)
36 {
37 return ( (int) ins[0] ) % 100;
38 }
main2.cpp
1 #include "hash2.h"
2 #include<iostream>
3 #include<iomanip>
4 #include<fstream>
5
6 using namespace std;
7
8 int main()
9 {
10 Hash hashTable;
11 hashTable.processFile("test1.txt");
12 hashTable.print();
13 }
So, what I have now is the processFile function, which takes the text file, reads each word in, performs the hash function(crappy, i know), then puts that word in the array index which the hash function returned. That is working fine I think.
What im having issues with is essentially using the STL list. So, in hash_function2.cpp, i want to print my hash table. I'm not sure how to check if the array index is empty(doesn't have any of the words I stored), and I am also not sure how to print all the strings in the list at a given array index. Basically what I would like to do is just print my hash table; get my print() function working.
If anyone could point me in the right direction that would be awesome! It would be greatly appreciated.
You shouldn't be checking for NULL because you have an array of std::list objects, not pointers.
You can check if the list at index i has any elements with:
if (!hashTable[i].empty())
{
// there are elements in the list
}
Or
if (hashTable[i].size())
{
// there are elements in the list
}
Also in your print() function, you're using an iterator of type std::list<int>, but it should be std::list<string>, which matches the declaration of hashTable.
Your problem is not with std list, it is with the array.
You could try using the std::array
#include <array>
std::array< std::list<string>, 100> hashTable;
this way you can check if it is emtpy
if (!hashTable.empty())
{
// do stuff
}
and inside you can check each list
if(!hashTable[i].empty())
{
// do even more stuff
}
Awesome, Thanks a lot guys! I understand how to check each array index and iterate through the list! Heres what I did:
1 #include "hash2.h"
2
3 #include<iostream>
4 #include<string>
5 #include<fstream>
6
7 using namespace std;
8
9 void Hash::processFile(string fileName)
10 {
11 string word;
12 ifstream myIfile(fileName.c_str());
13 while(getline(myIfile, word))
14 {
15 int index = hf(word);
16 hashTable[index].push_back(word);
17 }
18 myIfile.close();
19 }
20
21 void Hash::print()
22 {
23 for(int i = 0; i < 100; i++)
24 {
25 if(hashTable[i].empty() != true)
26 {
27 list<string>::iterator r;
28 for(r = hashTable[i].begin(); r != hashTable[i].end(); ++r)
29 {
30 cout << *r << endl;
31 }
32 }
33 }
34 }
35
36 int Hash::hf(string ins)
37 {
38 return ( (int) ins[0] ) % 100;
39 }
Related
I have a file which is made up of unknown rows but 2 columns and I would like to read this to a 2d vector, but I cannot achieve it, as my code skips the first columns all the time, i dont know why
I have written the code as follows:
#include <iostream>
#include <fstream>
#include <vector>
// this is for file handleing
using namespace std;
int main()
{
ifstream fp("test3_r.txt");
std::string token;
vector< vector<int> > vt1;
int x = 0;
char split_char = ' ';
int i =0;
std::vector<int> inner_vector;
while (std::getline(fp, token,split_char))
{
inner_vector.push_back(stoi(token));
if(i%2==1)
{
vt1.push_back(inner_vector);
inner_vector.clear();
}
i++;
}
for (int i = 0; i < vt1.size(); i++)
{
for (int j = 0; j < vt1[i].size(); j++)
{
cout << vt1[i][j];
cout << " ";
}
std::cout<<"\n";
}
fp.close();
return 0;
}
example of my input file:
0 3
0 7
0 10
0 16
0 23
0 25
0 26
0 28
0 30
1 17
1 18
2 18
2 25
3 0
3 10
3 11
3 16
3 19
3 25
3 28
3 31
4 10
4 18
4 25
5 0
5 9
5 10
5 11
5 16
5 18
5 23
5 25
5 28
6 0
6 1
6 4
6 9
6 10
6 11
6 12
6 15
6 16
6 18
6 23
6 25
6 27
6 28
6 30
7 0
7 18
7 22
7 23
7 25
The output i get is:
0 3
7 10
16 23
25 26
28 30
17 18
18 25
0 10
11 16
19 25
28 31
10 18
25 0
9 10
11 16
18 23
25 28
0 1
4 9
10 11
12 15
16 18
23 25
27 28
30 0
18 22
23 25
Which is not what i want. any help is appreciated
The problem is in the line
inner_vector.push_back(stoi(token));
What you thought you were doing was passing in things like "0" then "3", then "0" etc. But the thing is you were passing in things like "0", " 3\n0", " 7\n0". The getline ignores the endline and when passing in something like " 3\n0" into stoi it returns 3 and cuts off everything after the special character. My implementation is as follows:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
ifstream fp("f.txt");
string token;
vector< vector<int> > vt1;
while(getline(fp, token)){ // if you are given the size just do fp >>
vector<int> cols(2);
stringstream ss(token);
ss >> cols[0] >> cols[1];
vt1.push_back(cols);
cols.clear();
}
for (auto &i : vt1){
cout << i[0] << ' ' << i[1] << endl;
}
}
As far as I know you can't get getline to delimit more than one character so this is the next best solution.
You have overcomplicated your approach.
If your vector is only ever going to have 2 elements, using a std::vector to hold them is overkill. You could easily use a std::pair, std::tuple, or implement your own class Vector2D to hold the components. Using the latter would allow you to do something like the following:
std::vector<Vector2D> vt1;
vt1.assign(std::istream_iterator<Vector2D>(fp), std::istream_iterator<Vector2D>());
If there is some reason you must use a vector of vectors to hold your data, you can still accomplish it in an easier fashion:
int x, y;
while (fp >> x >> y)
{
std::vector<int> t {x, y};
vt1.push_back(t);
}
It is unnecessary to read in the line, and then try to parse the integers out of the lines. The extraction operator already does that for you.
Just so u know u dont need to use std:: when u have "using namespace std;", the whole point of using namespace is to avoid std::
I'm getting a memory access failure while i try to copy the element from my random array.
I have no clue what i am doing wrong, thx for your help in advance.
Here is my code:
1 #include <TSS_API_RNG.h>
2
3 using namespace std;
4
5 // dummy rng for internal speed tests
6 void rng(uint8_t out[], size_t len) {
7
8 unsigned char iv[len];
9 size_t i, k;
10 srand(time(NULL));
11 for (i = 0; i < len; i++) {
12 k = rand()%256;
13 iv[i] = (unsigned char)k;
14 cout << iv[i] << endl;
15
16 memcpy(&out[0], &iv[0], len);
17 cout << &out[0] << endl;
18 memset(&iv[0], 0x00, len);
19 }
20 }
21
22 int main() {
23
24 rng(NULL, 10);
25 return 0;
26 }
And this is what happens when i try to execute my programme:
pi#raspberrypi:~/projects/RNG_final $ ./DUMMY_RNG
▒
Speicherzugriffsfehler
I must be using the memcopy function not correctly, but i have no idea how to solve this issue. For testing i wanted to pass 10 random numbers, but it fails at the first iteration of memcpy. The loop itselfe works properly, hence it prints the value in the first cout value correctly.
Thx guys, managed to fix the issue with your advice.
My code:
1 #include <TSS_API_RNG.h>
2
3 using namespace std;
4
5 // constructor
6 DUMMY_RNG::DUMMY_RNG()
7 :r_len(0), r_count(0)
8 {
9 std::cout << "Neue Instanz" << std::endl;
10 }
11
12
13 // destructor
14 DUMMY_RNG::~DUMMY_RNG(void)
15 {
16 }
17
18
19 // dummy rng for internal speed tests
20 int DUMMY_RNG::rng(uint8_t out[], size_t len) {
21
22 unsigned char iv[len];
23 size_t k;
24 srand(time(NULL));
25 //for (i = 0; i < len; i++) {
26 k = rand()%256;
27 iv[0] = (unsigned char)k;
28
29 memcpy(&out[0], &iv[0], len);
30 memset(&iv[0], 0x00, len);
31 //}
32 return 1;
33 }
34
35
36 // randomize function replacement from botan rng class
37 void DUMMY_RNG::randomize(uint8_t out[], size_t len)
38 {
39 r_count += 1;
40 r_len += len;
41
42 rng(out, len);
43 }
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to create a program that will find a four-digit number that meets four specific requirements: all four digits are different, the thousands number is 3x the tens number, the number is odd, and the sum of the digits is 27. For some reason, despite the program compiling, the for loop won't run and always outputs the initializer number (1000). My main code and the four functions I'm calling are below. I can't figure out why it won't run correctly. I'm completely new to coding so any tips/help are appreciated. Thanks!
main function:
5 //prototypes
6 bool differentDigits(int);
7 bool thouThreeTen(int);
8 bool numberIsOdd(int);
9 bool sumIs27(int);
10
11 #include <iostream>
12 using namespace std;
13
14 int main ()
15 {
16 //variables
17 int n;
18
19 //processing
20
21 for(n=1000;n<=9999;n++)
22 {
23 if(differentDigits(n)==true)
24 {
25 break;
26 }
27
28 if(thouThreeTen(n)==true)
29 {
30 break;
31 }
32
33 if(numberIsOdd(n)==true)
34 {
35 break;
36 }
37
38 if(sumIs27(n)==true)
39 {
40 break;
41 }
42
43 }
44
45 //output
46 cout << n << endl;
47
48 return 0;
49 }
differentDigits function:
3 //Verify all four digits are the same
4
5 #include <iostream>
6 using namespace std;
7
8 bool differentDigits (int n)
9 {
10 int n1, n2, n3, n4;
11
12 n1 = n/1000;
13 n2 = (n/100) % 10;
14 n3 = (n/10) % 10;
15 n4 = n % 10;
16
17 if(n1 != n2 != n3 != n4)
18 {
19 return true;
20 }
21 else
22 {
23 return false;
24 }
25
26 }
thouThreeTen function:
3 //Verify digit in thousands place is 3x the digit in tens place
4
5 #include <iostream>
6 using namespace std;
7
8 bool thouThreeTen(int n)
9 {
10 int n1, n2, n3, n4;
11
12 n1 = n/1000;
13 n2 = (n/100) % 10;
14 n3 = (n/10) % 10;
15 n4 = n % 10;
16
17 if(n1 = (n3 * 3))
18 {
19 return true;
20 }
21 else
22 {
23 return false;
24 }
25
26 }
numberIsOdd function:
3 //Verify that the number is odd
4
5 #include <iostream>
6 using namespace std;
7
8 bool numberIsOdd (int n)
9 {
10 if((n % 2)==1)
11 {
12 return true;
13 }
14 else
15 {
16 return false;
17 }
18
19 }
sumIs27 function:
3 //Verify that the sum of digits is 27
4
5 #include <iostream>
6 using namespace std;
7
8 bool sumIs27(int n)
9 {
10 int n1, n2, n3, n4;
11
12 n1 = n/1000;
13 n2 = (n/100) % 10;
14 n3 = (n/10) % 10;
15 n4 = n % 10;
16
17 if((n1+n2+n3+n4)==27)
18 {
19 return true;
20 }
21 else
22 {
23 return false;
24 }
25
26 }
You have several problems with your code, the first being in main(). If any of the functions return true, you will end the loop. This is probably why you see the for loop as not being executed. Another problem is that in your functions, you are using conditions such as if(n1 = (n3 * 3)) which use the assignment operator instead of checking if they are the same.You want to use if(n1 == (n3 * 3)). Your main should look something like:
int main()
{
int n = 0;
for(n = 1000; n < 9999; ++n)
{
if(differentDigits(n) && thouThreeTen(n) && numberIsOdd(n) && sumIs27(n))
{
break;
}
}
cout << n << endl;
}
In each of your functions, make sure that you are using == not = when you are checking if something is a value.
So I am trying to solve the following question
Input Format is
N
x x x x x ...
q
y y y y y ...
N=size of array
x,x,x ... are elements of array
q=no of queries
y,y,y .. are queries to be searched in the array using binary search
Here is My code
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int N,q;
cin>>N;
int a[N];
for(int i=1;i<=N;i++)
{
cin>>a[i];
}
cin>>q;
int b[q];
for(int i=0;i<q;i++)
{
cin>>b[i];
}
int len=sizeof(a)/sizeof(a[1]);
sort(a,a+len);
int beg=1,end=N;
for(int j=0;j<q;j++)
{
beg=1;end=N;
while(beg<=end)
{
int mid=(beg+end)/2;
if(b[j]==a[mid])
{
cout<<mid<<endl;
break;
}
else if(b[j]<a[mid])
{
end=mid-1;
}
else
beg=mid+1;
}
}
return 0;
}
My code is giving the following output which is wrong
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
for the input
100
100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76 75 74 73 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
correct output is
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Arrays are 0-based.
Arrays are not variable-length in C++.
You have a wrong update here:
else if(b[j]<a[mid])
{
end=mid-1;
}
The end is non-inclusive.
You will also want to keep going until (beg<end) not beg<=mid - otherwise mid will simply equal both.
Here's C++ version that fixes all of the above and uses iterators instead of indexes. Iterators remove the ambiguity (base-0 vs base-1) and make it very explicit that a range is [begin, end), by contract.
Live ON Coliru
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main() {
int N;
cin >> N;
std::vector<int> a(N);
std::copy_n(std::istream_iterator<int>(std::cin), N, a.begin());
int q;
cin >> q;
std::vector<int> b(q);
std::copy_n(std::istream_iterator<int>(std::cin), q, b.begin());
sort(a.begin(), a.end());
for (auto query : b) {
auto beg = a.begin();
auto end = a.end();
while (beg < end) {
auto mid = beg + (end-beg) / 2;
if (query == *mid) {
cout << *mid << endl;
break;
} else if (query < *mid) {
end = mid;
} else beg = mid + 1;
}
}
}
Prints
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Problem 1
Your program has undefined behavior due to accessing a using an out of bounds index in the following loop.
for(int i=1;i<=N;i++)
{
cin>>a[i];
}
That loop needs to be changed to use a 0 based index.
for(int i = 0; i < N; i++)
{
cin >> a[i];
}
Problem 2
For similar reasons, the initial value of beg needs to be 0, not 1.
Problem 3
You are comparing with values of a[mid] but you are outputting mid. The output also needs to be a[mid].
Problem 4
else if(b[j]<a[mid])
{
end=mid-1;
}
needs to be
else if(b[j]<a[mid])
{
end=mid;
}
With the above changes, the program works as expected in my environment. Here's the updated program:
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int N,q;
cin>>N;
int a[N];
for(int i=0;i<N;i++)
{
cin>>a[i];
}
cin>>q;
int b[q];
for(int i=0;i<q;i++)
{
cin>>b[i];
}
int len=sizeof(a)/sizeof(a[1]);
sort(a,a+len);
int beg=0,end=N;
for(int j=0;j<q;j++)
{
beg=0;end=N;
while(beg<end)
{
int mid=(beg+end)/2;
if(b[j]==a[mid])
{
cout << a[mid] << endl;
break;
}
else if(b[j]<a[mid])
{
end=mid;
}
else
beg=mid+1;
}
}
return 0;
}
See it working at https://ideone.com/wgF2IS.
Array start with 0 index.so make sure for N elements your loop must start with zero index.
for(int i = 0; i < N; i++)
{
cin >> a[i];
}
Similarly, for same reason assign beg '0' value and end 'N-1' value.
I'm having a little trouble utilizing a map, and I have never really used them before so I am really struggling here
My Code is as follows:
MSTapp.h
5 #ifndef MSTAPP_H
6 #define MSTAPP_H
7
8 #include"Graph.h"
9
10 #include<iostream>
11 #include<map>
12 #include<vector>
13 #include<string>
14
15 using namespace std;
16
17 class MSTapp
18 {
19 public:
20 void read_graph();
21 void print_v();
22 // void print_e();
23
24 private:
25 Graph my_graph;
26 };
27
28 #endif
29
MSTapp.cpp
5 #include"MSTapp.h"
6 #include"Graph.h"
7
8 #include<iostream>
9 #include<map>
10 #include<vector>
11 #include<stdlib.h>
12 #include<sstream>
13 #include<string>
14
15 using namespace std;
16
17 void MSTapp::read_graph()
18 {
19 string s;
20 int count = 0;
21
22 while(getline(cin, s))
23 {
24 if(count == 0)
25 {
26 istringstream my_words(s);
27 string word;
28 while(my_words >> word)
29 {
30 my_graph.add_vertex(word);
31 }
32 }
33 else
34 {
35 string first;
36 string last;
37 int key;
38
39 first = s.substr(0, s.find(" "));
40 s.erase(0,s.find(" ")+1);
41 last = s.substr(0, s.find(" "));
42 s.erase(0,s.find(" ")+1);
43 key = atoi(s.c_str());
44
45 my_graph.add_edge(first, last, key);
46 }
47 }
48 }
49
50 void MSTapp::print_v()
51 {
52 my_graph.print_vertices();
53 }
Graph.h
5 #include"MSTapp.h"
6 #include<map>
7 #include<iostream>
8 #include<string>
9 #include<vector>
10 #include<list>
11
12 using namespace std;
13
14 #ifndef GRAPH_H
15 #define GRAPH_H
16
17 class Graph
18 {
19 public:
20 // Graph();
21 // ~Graph();
22 void add_vertex(string name);
23 void print_vertices();
24 void add_edge(string from, string to, int weight);
25 // void print_edges();
26 // void min_span_tree(string start);
27
28 private:
29 // MinPriority min_queue;
30
31 class Vertex
32 {
33 public:
34 string name;
35 string pi;
36 int key;
37 };
38 class Neighbor
39 {
40 public:
41 string name;
42 int weight;
43 };
44
45 vector<Vertex> vertices;
46 map <string name, list<Neighbor> > adj_list;
4
48 };
49
50 #endif
Graph.cpp
5 #include"MSTapp.h"
6 #include"Graph.h"
7
8 #include<iostream>
9 #include<map>
10 #include<algorithm> // sort
11 #include<string>
12 #include<vector>
13 #include<list>
14
15 using namespace std;
35 void Graph::add_vertex(string name)
36 {
37 Vertex v1;
38 v1.name = name;
39 v1.pi = "NIL";
40 v1.key = 100;
41 bool check;
42
43 for(int i = 0; i < vertices.size(); i++)
44 {
45 if(vertices[i].name == v1.name)
46 {
47 check = true;
48 }
49 }
50
51 if(check == false)
52 {
53 vertices.push_back(v1);
54 }
55 }
56
57 void Graph::print_vertices()
58 {
59 for(int i = 0; i < vertices.size(); i++)
60 {
61 cout << vertices[i].name << " " << vertices[i].pi << " " << vertices[i].key << endl;
62 }
63 }
64
65 void Graph::add_edge(string from, string to, int weight)
66 {
67 string v_from = from;
68 string v_to = to;
69 int v_weight = weight;
70
71 Neighbor n1;
72 n1.name = v_to;
73 n1.weight = v_weight;
74
75 adj_list[v_from];
76 adj_list[v_from].push_back(n1);
77 adj_list[v_from].sort();
78 }
All the functions for the Vertices are working so just ignore those. The main problem I am having is the add_edge function in the Graph. For example my input would be something as follows:
A B C D E //Vertices, this is working
A B 3
so, with the A B 3, I would like to add the B and 3 the the neighbor, and do something like
adj_list[A].push_back(Neighbor)
The errors I am getting are regarding the map, it is saying I have the incorrect number of template arguments for the map in Graph.h.
Am I declaring my map incorrectly on line 46 of Graph.h?
If anyone could provide any insight as to what I am doing wrong or how I can get this working it would be GREATLY appreciated. If any additional clarifcation is needed, just ask. Thanks!
you should declare the map as:
map <string, list<Neighbor> > adj_list;