Using combination algorithm to generate pairs of strings

Hello, I am looking to write all possible combinations of strings stored in a data structure. Here is what I've implemented so far, but I'd like to make it more efficient for larger cases.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
using namespace std;

int main() {
	string str[] = { "one", "two", "three", "four", "five" };

	cout << str[0] + str[1] << endl;
	cout << str[0] + str[2] << endl;
	cout << str[0] + str[3] << endl;
	cout << str[0] + str[4] << endl;
	cout << str[1] + str[2] << endl;
	cout << str[1] + str[3] << endl;
	cout << str[1] + str[4] << endl;
	cout << str[2] + str[3] << endl;
	cout << str[2] + str[4] << endl;
	cout << str[3] + str[4] << endl;

	return 0;
}
Last edited on
do combination of numbers.
i.e. 0,1,2,3,4
you get (i,j), (i,k)....
then str[i] + str[j] for (i,j) ...
@LB,

Thank you for the advice, I was able to create an implementation based on the next_permutation c++ method. Now, my problem is, I want to make the following line: array_2.push_back(array[i] + array[i+1] + array[i+2]); be more efficient so that it still stores the string when the vector size is more than 3 and etc.?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {
	int i=0;
	int j=0;
	vector<string> array;
	vector<string> array_2;

	array.push_back("one");
	array.push_back("two");
	array.push_back("three");

	do {
                // how do I make this more efficient for bigger cases?
		array_2.push_back(array[i] + array[i+1] + array[i+2]) ;
	} while (std::next_permutation(array.begin(), array.end()));

	for (j=0; j < array_2.size(); j++) {
		cout << array_2[j] << endl;
	}
}
Last edited on
You can use std::accumulate:
http://www.cplusplus.com/reference/numeric/accumulate/
http://en.cppreference.com/w/cpp/algorithm/accumulate
1
2
std::vector<std::string> v {"alpha", "beta", "gamma"};
std::string s = std::accumulate(std::begin(v), std::end(v), std::string{});
http://ideone.com/HhbYZr

http://stackoverflow.com/a/1986048/1959975
http://stackoverflow.com/a/15347181/1959975
Topic archived. No new replies allowed.