【发布时间】:2019-10-14 11:21:51
【问题描述】:
我正在创建一个拼字游戏,我需要对字典上的单词有一个基本的分数。
我使用 make_tuple 并将其存储在我的元组中。有没有办法像访问向量一样访问元组中的元素?
#include <iostream>
#include <tuple>
#include <string>
#include <fstream>
void parseTextFile()
{
std::ifstream words_file("scrabble_words.txt"); //File containing the words in the dictionary (english) with words that do not exist
std::ofstream new_words_file("test.txt"); //File where only existing words will be saved
std::string word_input;
std::tuple<std::string, int> tupleList;
unsigned int check_integrity;
int counter = 0;
while(words_file >> word_input)
{
check_integrity = 0;
for (unsigned int i = 0; i < word_input.length(); i++)
{
if((int)word_input[i] >= 97 && (int)word_input[i] <= 123) //if the letter of the word belongs to the alphabet
{
check_integrity++;
}
}
if(word_input.length() == check_integrity)
{
new_words_file << word_input << std::endl; //add the word to the new file
tupleList = std::make_tuple(word_input, getScore(word_input)); //make tuple with the basic score and the word
counter++; //to check if the amount of words in the new file are correct
std::cout << std::get<0>(tupleList) << ": " << std::get<1>(tupleList) << std::endl;
}
}
std::cout << counter << std::endl;
}
【问题讨论】:
-
不,
std::get是你的做法。但也许您希望std::pair具有first和second成员,甚至是std::map来执行查找? -
也许
std::map是我需要的。使用向量我会这样做:for (int i = 0; i < vector.size(); i++) { std::cout << vector[i] << std::endl; }我想做一些执行相同但如果可能的话使用元组的事情