所以说我有:
string array1[5] = {"A", "B", "C", "D", "F"};
string array2[5] = {"A", "C", "G", "F", "D"};
string result[100];
我试图使字符串结果[100]由array1和array2的非重复组成,同时按照array1 [0]然后是array2 [0]然后是array1 [1]然后是array2 [ 1]等。
(例如)string result[100] = {"A", "B", "C", "G", "D", "F"};
这是我到目前为止的代码:
for (i=0; i < 5; i++) {
result[i] = array2[i];
}
for (i=0; i<5; i++) {
for (j=0; j<100; j++) {
if (result[j] == "") {
result[j] = array1[i];
break;
}
if (result[j] == array1[i]) break;
}
}
此代码避免重复,但不按我想要的正确顺序。我无法解决这个问题。任何帮助将不胜感激。
答案 0 :(得分:2)
完全正常工作,我刚写完。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
string array1[5]= {"A","B","C","D","F"};
string array2[5]= {"A","C","G","F","D"};
vector<string> result;
bool check1;
bool check2;
for(int i=0; i<sizeof(array1)/sizeof(array1[0]);i++){
bool check1= check2= false;
if(result.size() == 0 && array1[i] != array2[i]){
result.push_back(array1[i]);
result.push_back(array2[i]);
}
else if(result.size() == 0 && array1[i] == array2[i]){
result.push_back(array1[i]);
}
else {
for(int j=0; j<result.size(); j++){
if(array1[i] == result[j])
check1= true;
}
if(!check1)
result.push_back(array1[i]);
for(int j=0; j<result.size(); j++){
if(array2[i] == result[j])
check2= true;
}
if(!check2)
result.push_back(array2[i]);
}
}
for(vector<string>::iterator it= result.begin(); it != result.end(); it++){
cout<<*it<<" ";
}
cout<<endl;
return 0;
}
答案 1 :(得分:0)
以下方法创建std::map
,以便仅保留唯一字符串,但也存储索引,以便可以使用正确顺序的元素创建第二个映射。
#include <string>
#include <vector>
#include <iostream>
#include <map>
int main()
{
std::vector<std::vector<std::string>> vec{
{"A", "B", "C", "D", "F", "W"},
{"A", "C", "G", "F", "D"}};
using Index = std::pair<size_t, size_t>;
std::map<std::string, Index> intermediate;
for(size_t row{}; row < vec.size(); ++row)
for(size_t element{}; element < vec[row].size(); ++element)
intermediate.insert(std::make_pair( // Won't overwrite
vec[row][element], // Insert string in map
Index{element, row})); // Store index for sequencing
std::map<Index, std::string> result;
for(auto&&[string, index] : intermediate) // C++17 structured bindings
result[index] = string; // Map sorts by original position
for(auto& element : result)
std::cout << element.second << ' ';
}