C++ vector programming help

Thanks for the help everyone, got a 100
Last edited on
I've applied some indentation to your code, I can't read what you posted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include<iostream>
#include<vector>
#include<string.h>
#include<string>

using namespace std;

class Hash
{
public:
    Hash() {
        for (int i = 0; i < 15; i++) {
            hashObject[i] = "*";
        }
    }

    void insert() { //insert a word into the Hash
        string t; int f; int s; int l; int location; int done = 0;
        cout<<"Insert Word: ";
        cin>>t;
        cout <<" the length of: " << t << " is " << t.length() << endl;

        f = t[0];
        s = t[1];
        l = t[t.length()-1];
        location = ((f)+(s)+(l))%15;

        while (done == 0) {
            if (hashObject[location] == "*") {
                hashObject[location] = t;
                done = 1;
            }
            else if (location != 14) {
                location++;
            }
            else {
                location = 0;
            }
        }
    }

    void out() { //output locations that are storing a word
        int check = 0;
        while (check < 15) {
            cout<<"Location "<<check<<": "<< hashObject[check]<<endl;
            check++;
        //}
        }
    }

    int check(string input) {//check hashObject for word
        int f; int s; int l; int location;

        f = input[0];
        s = input[1];
        l = input[input.length()-1];
        location = ((f)+(s)+(l))%15;

        while (hashObject[location] != "*") {
            //cout<<"Debugg"<<endl; //debugging line 3
            if (hashObject[location] == input) {
                return 1;
            }
            else if (location != 14) {
                location++;
            }
            else {
                location = 0;
            }
        }
        return 0;
    }

private:
    vector<string> hashObject = vector<string>(15);
};

int main(void) {
    Hash sarner; //creates new class of Hash

    for (int i = 0;i < 10; i++) { //user inputs into Hash
        sarner.insert();
    }

    sarner.out(); //return the vector of Hash

    string check;
    while (check != "*") {
        cout<<"Insert word to search for (typing * will terminate program): ";
        cin>>check;
        if (check != "*") {
            if(sarner.check(check) == 1) {
                cout<<check<<" is included in the list!"<<endl; }
            else{
                cout<<check<<" is not included in the list"<<endl;
            }
        }
    }
}
So basically I want to know if there is a way to improve my code, also I want to know when the user searches for the word can it display the position how do I do that? Does my code meet all the instructions?
You seem to have all the parts, so that's good.

Have you considered what happens if you try to input a string that's less than 3 characters?
What happens if your try to add a 16th string?

One neat improvement you can make, change Hash::insert. Rather that making that method read a string from the user, why not pass in the string to be added instead, and have the thing that calls it provide the string? That's what you do for Hash::check, right?

You seem to have these magic number throughout the code, 10, 14, 15. What do they represent? If you had to give them names, what would the names be?
Last edited on
It will still work if it is less than 3 characters, if you add a 16th string it wouldn't add to the vector cause it would be full since it holds only 15, Im not sure how I would implement that I am confused on what you mean, Not sure what you mean about the magic numbers whats wrong about them? They are positions in the vector.
Can you show me how to improve that code id be very happy to learn
I need to know how to print the position where it was found when the user searches that the only part im stuck on someone help me out please.
The code can be simplified. Note that there is no check for inserting after the array/vector is full. As C++20, consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Hash {
public:
	Hash() { }

	void insert() { //insert a word into the Hash
		string t;

		cout << "Insert Word: ";
		cin >> t;

		cout << " the length of: " << t << " is " << t.length() << '\n';

		for (auto location{ hash(t) }; true; location = (location + 1) % sze)
			if (hashObject[location].empty()) {
				hashObject[location] = t;
				break;
			}
	}

	void out() {
		for (size_t check{}; const auto& o : hashObject)
			cout << "Location " << check++ << ": " << (o.empty() ? "<Not used>" : o) << '\n';
	}

	size_t check(const string& input) {
		for (auto location{ hash(input) }; !hashObject[location].empty(); location = (location + 1) % sze)
			if (hashObject[location] == input)
				return location + 1;

		return 0;
	}

private:
	size_t hash(const std::string& t) {
		const auto f{ t[0] };
		const auto s{ t.size() > 1 ? t[1] : t.back() };
		const auto l{ t.back() };

		return (f + s + l) % sze ;
	}

	constexpr static size_t sze{ 15 };
	vector<string> hashObject {vector<string>(sze)};
};

int main(void) {
	Hash sarner;

	std::cout << "Please enter 10 words\n";

	for (size_t i = 0; i < 10; ++i)
		sarner.insert();

	sarner.out();

	for (string check; check != "*"; ) {
		cout << "Insert word to search for (typing * will terminate program): ";
		cin >> check;

		if (check != "*")
			if (auto pos {sarner.check(check)}; pos)
				cout << check << " is included in the list! - at position " << pos - 1 << '\n';
			else
				cout << check << " is not included in the list" << '\n';
	}
}

Last edited on
It will still work if it is less than 3 characters
1
2
3
4
        f = t[0];
        s = t[1];
        l = t[t.length()-1];
        location = ((f)+(s)+(l))%15;

What if t is "H"?

if you add a 16th string it wouldn't add to the vector cause it would be full since it holds only 15, Im not sure how I would implement that I am confused on what you mean
You drop into an infinite loop, the program hangs. Have you tested it? How can you stop it from hanging?

Not sure what you mean about the magic numbers whats wrong about them?
https://en.wikipedia.org/wiki/Magic_number_(programming)

Hash::out, it's writes to std::cout, but it could write to any stream if the actual output stream was passed as a parameter.

That hash function should be pulled out into a separate method, should it need to be changed later on, it'll be easy to find.

Other than that, it's pretty good.
Last edited on
It needs to be in the original format can't be c++ 20 standard how do I fix my original code so that it searches for the location? Please help me out no one is helping, the assignment doesn't require me to test less than 3 letters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
searches for the location?, 
it is, in pseudo code..
if hashtable[hashfunction(data)] == data //the location is hashfunction(data), return it
if the above location is empty, the data is not in the table. (assumption:no deleting from table)
return -1 //tells you its not in the table, -1 not a valid index

if the location is used and does not match (no condition here, you know this from above and only get here by not returning a value so far)
for(i = hashfunction(data)+1; the size of the table -1; )
{
   if(hashtable[i] == data) return i;
   if(hashtable[i] is not used) return -1;
    i = (i+1)%hashtablesize;
}
return -1; //if you ran the whole for loop and got here, its not there 


linear searching negates a lot of the point. Better to ensure your table is big enough that your data does not collide.
Last edited on
So my code does a linear search? It won't let me print the code to the search it keeps giving me a error saying the variable doesn't exist how do I fix it can you give me my code fixed so I can see how it is done it's hard to understand that way.
also I want to know when the user searches for the word can it display the position how do I do that?
Sorry, I missed that question.

Ok, you already have everything. That check() methods does that, right? It just doesn't display the index, which is variable location.

If you want check() to return the location, you can make it return the index, or -1 if it's not found.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    int check(string input) {//check hashObject for word
        int f; int s; int l; int location;

        f = input[0];
        s = input[1];
        l = input[input.length()-1];
        location = ((f)+(s)+(l))%15;

        while (hashObject[location] != "*") {
            //cout<<"Debugg"<<endl; //debugging line 3
            if (hashObject[location] == input) {
                return location;
            }
            else if (location != 14) {
                location++;
            }
            else {
                location = 0;
            }
        }
        return -1;
    }

Then use that value.
1
2
3
4
5
6
7
8
9
10
11
12
13
    string check;
    while (check != "*") {
        cout<<"Insert word to search for (typing * will terminate program): ";
        cin>>check;
        if (check != "*") {
            int index = sarner.check(check);
            if(index != -1) {
                cout<<check<<" is included in the list at position " << index <<endl; }
            else{
                cout<<check<<" is not included in the list"<<endl;
            }
        }
    }
Last edited on
Awesome, I feel like I am not allowed to do a linear search on this, so I feel like this step is wrong, C) repeatedly query the user for a target word, hash the word, check for its inclusion in the list of stored words, and report the result. Continue doing this task until the user signals to stop (establish a sentinel condition). I believe we need to do all of this with hashing so for the search function when the user inputs the word its suppose to hash it then check if its in the list of words and report the results. How can I fix this can anyone help me out?
the bad design (not you, the problem statement) forces you to do a linear search.

In this example, an attempt would be made to store "rocky" in position 1. In the event of a collision, the word would be stored in the first available location, so if there is a collision in location 1, an attempt would be made to store the word in location 2. If there is a collision in location 2, try location 3 and so on. If there is a collision in location 14, cycle back to location 0.


^^^ That means you have to do it. It can't be avoided ... there are other ways to hash data that avoid this, but you were told to do it this way. One way is to make each hash table location a container, and just stack up the collisions. Then if you have a million items, and have to search through 10 of them, so what? Its fast.
Last edited on
Please do NOT delete your question once you've gotten an answer. It makes the thread useless as a learning resource for others.
Topic archived. No new replies allowed.