【发布时间】:2019-11-05 10:20:57
【问题描述】:
我的程序有两个名字和年龄向量。它对名称向量进行排序,并以正确的顺序保持年龄向量以匹配排序后的名称向量。现在,我想从现有代码中创建一个函数,但我遇到了一些问题。
现有代码:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iomanip>
using namespace std;
int main() {
vector<string> names {"One", "Two", "Three", "Four", "Five"};
vector<unsigned int> ages { 1, 2, 3, 4, 5};
const vector<string> namesCopy = names;
sort(begin(names), end(names));
decltype(ages) sortedAges(ages.size());
for(int i = 0; i < namesCopy.size(); ++i) {
const auto iter = lower_bound(begin(names), end(names), namesCopy[i]);
const auto pos = iter - begin(names);
sortedAges[pos] = ages[i];
}
for(int i = 0 ; i < names.size() ; ++i)
cout << setw(10) << names[i] << setw(4) << sortedAges[i] << '\n' ;
}
功能:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iomanip>
using namespace std;
int test(vector<string> testNames, vector<string> testNamesCopy, vector<unsigned int> testAges, vector<unsigned int> testSortedAges) {
for(int i = 0; i < testNamesCopy.size(); ++i) {
const auto iter = lower_bound(begin(testNames), end(testNames), testNamesCopy[i]);
const auto pos = iter - begin(testNames);
return testSortedAges[pos] = testAges[i];
}
}
int main() {
vector<string> names {"One", "Two", "Three", "Four", "Five"};
vector<unsigned int> ages { 1, 2, 3, 4, 5};
const auto namesCopy = names;
sort(begin(names), end(names));
decltype(ages) sortedAges(ages.size());
for(int i = 0 ; i < names.size() ; ++i)
cout << setw(10) << names[i] << setw(4) << test(names, namesCopy, ages, sortedAges) << '\n' ;
}
【问题讨论】:
-
您的两个输出图像是同一个文件。其次,函数中的 for 循环将在第一次迭代后结束,因为函数在该点返回。所以让我在这里澄清一下:
returnends 函数一旦发生。它不会积累任何东西或类似的东西。 -
除此之外,您的算法对我来说似乎很乏味。如果要将两个向量归为一个,请从类型中创建一个结构,例如
struct Entry { string name; unsigned int age; };和函数bool lesser(const Entry& a, const Entry& b) { return a.age < b.age; },然后对于vector<Entry> entries,调用std::sort(entries.begin(), entries.end(), lesser),另请参阅 stackoverflow.com/questions/1380463/…