Reputation: 5
I have array masiv_C0 = {{AB, ADF}, {BC, ADF}, {CD, BC}, {DE, ADF}}
I have array masiv_X0 = {{AB, ADF}, {CD, BC}, {DE, ADF}}
It is necessary to create a third array of the first two:
masiv_Y1 = masiv_C0 - masiv_X0 = {{BC, ADF}}
The problem is that in the third array which I create I delete individual elements.
As a result, rather than to obtain {{BC, ADF}} I get {{BC}} ... Help correct code! Thanks :)
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
typedef std::vector<std::string> String1D;
typedef std::vector<String1D> String2D;
int main()
{
String2D masiv_C0(4, String1D(2));
masiv_C0[0][0]="AB";
masiv_C0[0][1]="ADF";
masiv_C0[1][0]="BC";
masiv_C0[1][1]="ADF";
masiv_C0[2][0]="CD";
masiv_C0[2][1]="BC";
masiv_C0[3][0]="DE";
masiv_C0[3][1]="ADF";
String2D masiv_X0(3, String1D(2));
masiv_X0[0][0]="AB";
masiv_X0[0][1]="ADF";
masiv_X0[0][0]="CD";
masiv_X0[0][1]="BC";
masiv_X0[0][0]="DE";
masiv_X0[0][1]="ADF";
String2D masiv_Y1 = masiv_C0;
for ( size_t i = 0; i < masiv_X0.size(); ++i)
{
for ( size_t j = 0; j < masiv_X0[i].size(); ++j)
{
auto& str = masiv_X0[i][j];
for (size_t cur = 0; cur < masiv_Y1.size(); ++cur)
{
auto iter = std::remove(masiv_Y1[cur].begin(), masiv_Y1[cur].end(), str);
masiv_Y1[cur].erase(iter, masiv_Y1[cur].end());
}
}
}
String2D::iterator iter = masiv_Y1.begin();
while (iter != masiv_Y1.end())
{
std::copy((*iter).begin(), (*iter).end(), std::ostream_iterator<std::string>(cout, " "));
cout << "\n";
++iter;
}
return 0; }
Upvotes: 0
Views: 47
Reputation: 33932
X-Y answer: Throw out what you are doing. The standard library does everything you need to do for you. No muss. No fuss.
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
// shorten this templated nightmare
using vecpair = std::vector<std::pair<std::string,std::string>>;
// define inputs
vecpair masiv_C0{{"AB","ADF"},{"BC","ADF"},{"CD","BC"},{"DE","ADF"}};
vecpair masiv_X0{{"AB","ADF"},{"CD","BC"},{"DE","ADF"}};
// define output
vecpair masiv_Y1;
// use std library to do the work
std::set_difference(masiv_C0.begin(), masiv_C0.end(),
masiv_X0.begin(), masiv_X0.end(),
std::back_inserter(masiv_Y1));
// print it.
for (const std::pair<std::string,std::string> & p: masiv_Y1)
{
std::cout << "{" << p.first << "," << p.second << "}\n";
}
return 0;
}
Addendum note:
Everything above except the print loop should work with std::vector<std::vector<std::string>>
as well should be vector
of vector
be an external, and performance-killing, requirement.
Upvotes: 1