C++学习笔记 20 pair tuple array vector 实现多返回值

#include<iostream>
#include<array>
#include<vector>
#include<string>

void testStdPair() {
	std::pair<std::string, std::string> pair = std::make_pair("aaa", "bbb");
	std::cout << std::get<0>(pair) << " | " << std::get<1>(pair) << std::endl;
	std::cout << pair.first << " | " << pair.second << std::endl;
}

void testStdTuple() {
	std::tuple<std::string, std::string, int, float> tuple = std::make_tuple("hello", "world", 10, 5.6f);
	std::cout << std::get<0>(tuple) << " | " << std::get<1>(tuple) << " | " << std::get<2>(tuple) << std::endl;
}

//数据在栈上
std::array<std::string, 2> testArray() {
	std::array<std::string, 2> arr;
	arr[0] = "hello";
	arr[1] = "world";
	for (std::string& str : arr) {
		std::cout << "array: " << str << std::endl;
	}
	return arr;
}

//数据在堆上
std::vector<std::string> testVector1() {
	std::vector<std::string> vct(2);
	//以下两种赋值方式皆可
//	vct[0] = "hello";
//	vct[1] = "world";

	vct.at(0) = "world";
	vct.at(1) = "hello";
	
	for (std::string& str : vct) {
		std::cout << "vector1: " << str << std::endl;
	}

	return vct;
}

//此处vet后不要再接(size)了,否则有复制。 用var[i]或 var.at(i)的方式赋值会报错,但可以取值
std::vector<std::string> testVector2() {
	std::vector<std::string> vct;
	vct.reserve(2);
	vct.emplace_back("hello");
	vct.emplace_back("world");

	for (std::string& str : vct) {
		std::cout << "vector2: " << str << std::endl;
	}
	std::cout << "vector3: " << vct[0] << std::endl;
	std::cout << "vector3: " << vct[1] << std::endl;
	return vct;
}


int main() {
	testStdPair();
	testStdTuple();
	testArray();
	testVector1();
	testVector2();
	std::cin.get();
}
posted @ 2025-12-16 15:20  超轶绝尘  阅读(1)  评论(0)    收藏  举报