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2 -3 -2 0 4 -3 -1
W -3 -2 -4 -3 1 -2 -2 -3 -3 -2 -1 -4 -4 -2 -3 -3 -2 -3 11 2
Y -2 -2 -3 -2 3 -3 2 -1 -2 -1 -1 -2 -3 -1 -2 -2 -2 -1 2 7
但是我在填充地图时遇到麻烦问题
static void gen_matrix(map<string, int>& mat)
{
const string myfile = "myfile.dat";
vector<string> myChars = { "A", "C", "D", "E", "F", "G", "H", "I", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "Y" };
ifstream f(myfile);
string temporal;
getline(f, temporal); // Ignore first string
while (getline(f, temporal))
{
auto buff(split_string(temporal));
auto prefix = buff[0];
size_t i = 1;
//try 1
// for(auto it = myChars.begin(), end = myChars.end(); it != end; ++it){
// mat[prefix + it] = stoi(buff[i++]);
// }
//try 2
//for(auto& var = 0; myChars){
// mat[prefix + var] = stoi(buff[i++]);
//}
}
}
我想要实现的是每项功能
for each (const auto& var in myChars)
{
mat[prefix + var] = stoi(buff[i++]);
}
但没有成功,如何改变循环?
答案 0 :(得分:1)
由于您没有展示split_string
,如果我理解正确,您可以尝试以下操作:
std::vector<std::string> split(const std::string &s) {
std::stringstream ss(s);
std::string item;
std::vector<std::string> elems;
while (ss >> item) {
elems.push_back(item);
}
return elems;
}
std::string temporal;
std::getline(fin, temporal,'\r'); // You may need this carriage return as delim
std::map<std::string, int> mat;
std::vector<std::string> buff;
while(std::getline(f, temporal,'\r'))
{
buff = split( temporal) ;
for(std::size_t x=1; x < buff.size() ; ++x)
mat[buff[0]+myChars[x-1]] = atoi( buff[x].c_str() );
}
答案 1 :(得分:1)
我建议不要使用getline读取行,而是使用IO运算符,如下所示:
ifstream f(myfile);
f.ignore( INT_MAX, '\n' );
while (f.good()){
string prefix;
f >> prefix;
for ( const string var : myChars){
int val;
f >> val;
mat[prefix + var] = val;
}
f >> ws;
}