我想在一个数组中交换一个数据,在另一个数组中交换平均数,同时跟踪计数和交换的值。
{2, 3, 6}
{1, 4, 7}
will become
{1, 3, 7}
{2, 4, 6}
有2个交换,交换的值是
1
& 2
,6
& 7
。
int main() {
int a1[3] = { 2, 3, 6 };
int a2[3] = { 1, 4, 7 };
int i;
int swapcount = 0;
int swapvalue;
std::cout << "Before swap:\n" << endl;
std::cout << "Array 1:\n" << endl;
for (int i = 0; i < 3; i++) {
cout << " " << a1[i] << endl;
}
std::cout << "Array 2:\n" << endl;
for (int i = 0; i < 3; i++) {
std::cout << " " << a2[i] << endl;
}
for (int i = 0; i < 3; i++) {
if (a1[i] % 2 != 1) {
swapcount++;
int temp = a1[i];
a1[i] = a2[i];
a2[i] = temp;
swapvalue = i;
}
}
std::cout << "After swap:\n" << endl;
std::cout << "Array 1:\n" << endl;
for (int i = 0; i < 3; i++) {
std::cout << " " << a1[i] << endl;
}
std::cout << "Array 2:\n" << endl;
for (int i = 0; i < 3; i++) {
std::cout << " " << a2[i] << endl;
}
std::cout << "swap count: " << swapcount << endl;
std::cout << "swap value: " << swapvalue << endl;
}
到目前为止,我已经让swap
和counter
工作,但我似乎无法弄明白:
如何查找和存储交换元素的各个值? (我只能显示一个值。)
我可以获得有关如何全部获取值的任何提示吗?除输入和输出流外,我不允许使用任何其他库。提前谢谢。
答案 0 :(得分:1)
创建一个辅助数组swapbool,如果完成交换,则设置boolean = 1。
from py2neo import Graph
graph = Graph()
graph.cypher.execute("CREATE (n:Person) SET n = {props} RETURN n", props={"x":1,"y":2})
| n
---+-----------------------
1 | (n6:Person {x:1,y:2})
答案 1 :(得分:0)
有很多方法可以做到这一点。最简单的解决方案是将它们存储在std::vector
的{{1}}中:
std::pair
然后插入:
std::vector<std::pair<int, int>> swapvalues;
顺便说一下,在您的代码中存储索引,而不是值。如果要存储索引,请仅使用swapvalues.emplace_back(val1, val2);
整数。
答案 2 :(得分:0)
如何查找交换元素的各个值?
交换时,元素存储其索引:
int swappedValuesIndex[];
for (int i = 0; i < 3; i++) {
if (a1[i] % 2 != 1) {
// store swapped values' index
swappedValuesIndex[swapcount] = i;
swapcount++;
int temp = a1[i];
a1[i] = a2[i];
a2[i] = temp;
swapvalue = i;
}
}
// print swapped values
for (int i = 0; i < swapcount; i++){
cout <<"a1["<< swappedValuesIndex[i] <<"]"<< a1[swappedValuesIndex[i]] <<'\n';
cout <<"a2["<< swappedValuesIndex[i] <<"]"<< a2[swappedValuesIndex[i]] <<'\n';
}