對不起,如果這篇文章不是最好的,我是全新的網站和編碼的一般。我的節目以「Sam 16 Emily 4 Molly 19」的形式輸入並按字母順序排序,同時保持年齡相同。它的作用就像魅力,除非你輸入5對以上。輸入5後,以下名稱排序良好,但年齡並非正確。我不確定代碼在哪裏得到它輸出的數字。這是我的代碼。我很抱歉發佈一切(〜30行),但我真的不知道問題出在哪裏。C++:按字母順序排列名稱/年齡對,只能管理5對
#include"../std_lib_facilities.h"
vector<string> name;
vector<int> age;
void read_pairs()
{
string n;
int v;
while (cin >> n >> v && n != "NoName") { // read string int pair
for (int i = 0; i<name.size(); ++i)
name.push_back(n);
age.push_back(v);
}
}
void write_pairs(string label)
{
cout << label;
for (int i = 0; i<name.size(); ++i)
cout << '(' << name[i] << ',' << age[i] << ")\n";
}
int find_index(const vector<string>& v, const string& n)
// find n's index in v
{
for (int i = 0; i<n.size(); ++i)
if (n == v[i]) return i;
}
int main()
try
{
cout << "Please enter your name/age pairs. When finished, enter 'No More'\n";
read_pairs();
vector<string> original_names = name; // copy the names
vector<int> original_ages = age; // copy the ages
sort(name.begin(), name.end()); // sort the names
for (int i = 0; i<name.size(); ++i) // update ages
age[i] = original_ages[find_index(original_names, name[i])];
write_pairs("\nSorted:\n");
keep_window_open("~");
}
catch (runtime_error e) {
cout << e.what() << '\n';
keep_window_open("~");
}
catch (...) {
cout << "exiting\n";
keep_window_open("~");
}
我認爲你的問題與通過引用分配向量的方式有關。很快就會發布答案。 – Hosch250 2014-10-09 02:40:43
這不可能工作 - 由於這個循環,'name'向量總是空的:'for(int i = 0; i
2014-10-09 02:42:13
@ hosch250:我不太清楚你在想什麼,但是「std :: vector'不是」通過引用分配「。 – Blastfurnace 2014-10-09 03:06:42