C ++将向量插入向量覆盖而不是push_back

时间:2017-10-25 09:11:01

标签: c++ vector

<?php
	session_start();
	$game = $_SESSION['sale_game'];
	$qty = $_SESSION['sale_qty'];
	$price = $_SESSION['sale_price'];
	$subtotal = $_SESSION['sale_subtotal'];
	$fName = $_POST['fName'];
	$lName = $_POST['lName'];
	$address = $_POST['address'];
	$city = $_POST['city'];
	$state = $_POST['state'];
	$zip = $_POST['zip'];
	$email = $_POST['email'];
	$con = new mysqli('localhost', 'root', 'root', 'purchases');
	if (!$con) {
		echo "Not connected to database";
	} else {
		$query = "INSERT INTO orders (Game, Price, Quantity, Total, fName, lName, Address, City, State, Zip, Email) VALUES ('$game', '$price', '$qty', '$subtotal', '$fName', '$lName', '$address', '$city', '$state', '$zip', '$email')";
		if ($con->query($query) === TRUE) {
			echo "Inserted";
		} else {
			echo "Not Inserted";
		}
	}
?>
<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style>
		* {
			margin: 0;
			padding: 0;
		}

		#container {
			top: 50%;
			left: 50%;
			position: absolute;
			border: 1px solid black;
		}
	</style>
</head>
<body>
	<div id="container">
		<p> 
		</p>
	</div>
</body>
</html>

说我有两个向量:网格和船。我想将船插入网格并根据我选择的位置覆盖原始值。例如,如果位置是2,我应该得到 eefffeeeee 如果位置是5,我应该得到eeeeefffee

4 个答案:

答案 0 :(得分:9)

std::copy(ship.begin(), ship.end(), grid.begin() + offset);

这会覆盖元素。小心不要超出范围。

答案 1 :(得分:2)

试试这个(包括健全性检查):

#include <iostream>
#include <vector>

void overwriteVectorWithOffset(std::vector<char> &target, std::vector<char> const &source, size_t offset)
{
    size_t end = min(target.size(), source.size() + offset);
    size_t i = 0;

    while (offset < end)
        target[offset++] = source[i++];
}

int main()
{
    std::vector <char> grid(10, 'e');
    std::vector <char> ship(3, 'f');

    overwriteVectorWithOffset(grid, ship, 2);

    for (size_t i = 0; i < grid.size(); ++i)
        std::cout << grid[i];

    std::cout << std::endl;
 }

答案 2 :(得分:2)

您可以使用std::copy_n进行作业。您只需将count设为[ship.begin(), ship.end()][grip.begin() + location, grip.end()]之间的最小距离即可。这样可以确保不会出现超出范围的错误。

在代码中(顺便说一句,仅假设位置为正,否则将需要进一步检查):

// Sanity check
auto offset = std::min(grid.begin() + location, grid.end());

// calculating count, as described above
auto grid_distance = std::distance(offset, grid.end());
auto ship_distance = std::distance(ship.begin(), ship.end());
auto count = std::min(grid_distance, ship_distance);

std::copy_n(ship.begin(), count, offset);

答案 3 :(得分:0)

#include <iostream>
#include <algorithm>
#include <vector>

std::vector<char> grid(10, 'e');
std::vector<char> ship(3, 'f');

void InsertShip(int position)
{
    if (position >= 0 && position < grid.size())
        std::transform(ship.begin(), ship.end(), grid.begin() + position, 
            [](const char& ch) { return ch; });
}

int main()
{
    InsertShip(2);

    for (const auto& ch : grid)
        std::cout << ch;

    getchar();
}