how to create a 2D vector: first row of string and second row is integer

how can i make a vector where the first row is of string and second row is of integers ?
where each number represents number of occurence of each word


this adam dad hello
 2    4    1    6

Stack Overflow Asked by KingAzaiez on November 15, 2021

2 Answers

2 Answers

There are some possibilities.

If you care for the order of the elements:

vector<pair<string, int>> occurrences;

int main(){
    occurrences.push_back( make_pair("this", 2) );
    occurrences.push_back( make_pair("adam", 4) );
    //access: occurrences[0].first or occurrences[0].second


map<string, int> occurrences;             //O(logN) insertion and lookup
unordered_map<string, int> occurrences;   //O(1) insertion and lookup
int main(){
    occurrences["this"] = 2;
    occurrences["adam"] = 4;

If you want something elaborated, you can use struct:

struct occurrence{
    string word;
    int value;
    occurrence(string w, int v){word = w; value = v;}

occurrence ocurrences[10];

int main(){
    ocurrences[0] = ocurrence("this", 2);
    ocurrences[1] = ocurrence("adam", 4);

Answered by Daniel on November 15, 2021

I find it most convenient to create a vector of struct ... or, as the case may be, classes. One field is the name; the other is the count. Access by e.g. vector[n].word or vector[n].wordCount. The virtue of this approach is that it's easy to add more fields at any time.

Answered by Mike Robinson on November 15, 2021

Add your own answers!

Related Questions

Ask a Question

Get help from others!

© 2021 All rights reserved.