Reputation: 113
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
Example:
this adam dad hello
2 4 1 6
Upvotes: 0
Views: 196
Reputation: 7714
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
}
Otherwise:
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(){}
occurrence(string w, int v){word = w; value = v;}
};
occurrence ocurrences[10];
int main(){
ocurrences[0] = ocurrence("this", 2);
ocurrences[1] = ocurrence("adam", 4);
}
Upvotes: 2
Reputation: 8945
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.
Upvotes: 1