vector of a vector with char index

Hello,

I am trying to write a program that calculates the score of 2 strings. One time without inserting spaces, and another with spaces. This part is straightforward. The scores are stored in a matrix, so I need to use a 2 dimensional vector, or a vector of a vector.

Scores are indexed by letters and based on these letters that I am going to get from the strings entered. For example:
score[b][u] = 12
score[k][p] = 3
score[r][ ] = 0
score[z][m] = -5
score[ ][s] = 1

I am stuck in two issues:
First one is using a char as a vector index.
Second is storing and comparing to calculate scores.

Thank you,
Last edited on
char is an integral type, so you can use it as index variable:
1
2
3
std::vector<std::vector<int>> foo(128, std::vector(128));
foo['a']['b'] = 100;
std::cout << foo['a']['b'] << '\n';
http://coliru.stacked-crooked.com/a/898f6dba3a6e445d

Thanks MiiniPaa,
I tried the snippet you posted. The program compiled with no errors, so I thought it was going to work, but when I run the program, I get this stupid error that the program stopped working. I think there is a runtime error.

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
#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    string s1, s2;

    char with_spaces;
    vector<vector<int>> pam;
    pam ['a']['v'] = 7;
    cout << pam ['a']['v'] << endl;
    cout << "Enter the first sequence:" << endl;
    cin >> s1;

    cout << "Enter the second sequence:" << endl;
    cin >> s2;

    cout << "Do you want to insert spaces to the second sequence? y/n" << endl;
    cin >> with_spaces;

    vector<char> seq1 (s1.begin(), s1.end());
    vector<char> seq2 (s2.begin(), s2.end());


    if (with_spaces == 'y') {

        vector<char> new_seq2;
        for(vector<char>::const_iterator i = seq2.begin(); i != seq2.end(); ++i) {
            new_seq2.push_back(*i);
            new_seq2.push_back(' ');
        }

        seq2 = new_seq2;

    }



    for (vector<char>::const_iterator i = seq1.begin(); i != seq1.end(); ++i) {
        cout << *i;
    }

    cout << endl;

    for (vector<char>::const_iterator i = seq2.begin(); i != seq2.end(); ++i) {
        cout << *i;
    }


    return 0;
}
vector<vector<int>> pam; Vector pam is empty, it does not have elements at all. So accessing vec['a'] is not going to work, as there is no element 48 ('a' code). You will need to allocate some elements to it (what I did in my snippet)

Alternatively, there is a better solution: use a map.
http://coliru.stacked-crooked.com/a/5318d55acbb9a644
Last edited on
I did it this way at first but the code did not compile
std::vector<std::vector<int>> pam (128, std::vector(128));
Missing template argument before ( token
Check the link in that post, there is a correct version.
Thank you..

Last edited on
Topic archived. No new replies allowed.