就地生成 2 个向量的笛卡尔积<string>?
Generate the Cartesian Product of 2 vector<string>s In-Place?
如果我想得到这两个vector<string>
的笛卡尔乘积:
vector<string> final{"a","b","c"};
vector<string> temp{"1","2"};
但我想把结果放在final
中,这样最终会包含:
a1
a2
b1
b2
c1
c2
我希望在不创建临时数组的情况下执行此操作。有可能做到这一点吗?如果重要的话,final
的顺序并不重要。
您可以尝试以下方法
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> final{ "a", "b", "c" };
std::vector<std::string> temp{ "1", "2" };
auto n = final.size();
final.resize( final.size() * temp.size() );
for ( auto i = n, j = final.size(); i != 0; --i )
{
for ( auto it = temp.rbegin(); it != temp.rend(); ++it )
{
final[--j] = final[i-1] + *it;
}
}
for ( const auto &s : final ) std::cout << s << ' ';
std::cout << std::endl;
return 0;
}
程序输出为
a1 a2 b1 b2 c1 c2
尝试函数cartesian:
#include <vector>
#include <string>
using namespace std;
void cartesian(vector<string>& f, vector<string> &o) {
int oldfsize = f.size();
f.resize(oldfsize * o.size());
for (int i = o.size() - 1; i>=0; i--) {
for (int j = 0; j < oldfsize; j++) {
f[i*oldfsize + j] = f[j] + o[i];
}
}
}
int main()
{
vector<string> f{"a","b","c"};
vector<string> temp{"1","2"};
cartesian(f, temp);
for (auto &s: f) {
printf("%sn", s.c_str());
}
}
这对我有效:
void testCartesianString(vector<string>& final,
vector<string>const& temp)
{
size_t size1 = final.size();
size_t size2 = temp.size();
// Step 1.
// Transform final to : {"a","a","b","b","c","c"}
final.resize(size1*size2);
for ( size_t i = size1; i > 0; --i )
{
for ( size_t j = (i-1)*size2; j < i*size2; ++j )
{
final[j] = final[i-1];
}
}
// Step 2.
// Now fix the values and
// change final to : {"a1","a2","b1","b2","c1","c2"}
for ( size_t i = 0; i < size1; ++i )
{
for ( size_t j = 0; j < size2; ++j )
{
final[i*size2+j] = final[i*size2+j] + temp[j];
cout << final[i*size2+j] << " ";
}
cout << endl;
}
}
这只是莫斯科解决方案中瓦尔的个人偏好选项。我认为动态数组可能更快,因为分支更少。但我还没来得及写一个计时测试台。
给定输入vector<string> final
和vector<string> temp
:
const auto size = testValues1.first.size();
testValues1.first.resize(size * testValues1.second.size());
for (int i = testValues1.first.size() - 1; i >= 0; --i){
testValues1.first[i] = testValues1.first[i % size] + testValues1.second[i / size];
}
编辑:
不,这个解决方案不是更快而是更慢:http://ideone.com/e.js/kVIttT
而且通常明显更快,尽管我不知道为什么。。。
无论如何,从莫斯科的回答中选择Vlad
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 为std::string的某个索引赋值
- <<操作员在下面的行中工作
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 使用char类型将decimal转换为string,将string转换为decimal
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 将向量解析<string>为字符串
- 'string.assign(string.data(), 5)' 是明确定义的还是 UB?
- 如何更改大小(std::string)
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- std::string 的对象真的可以移动吗?
- 与'operator='不匹配(操作数类型'String'且"void")
- SegFault 同时使用 std::string::operator+= 和函数作为参数